wined3d: Allow using more than MAX_COMBINED_SAMPLERS texture image units.
[wine.git] / dlls / wined3d / context.c
blob42b12458b30b1e5c5d5ec88f16d2bb5672300963
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 flags, GLuint rb)
108 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
110 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
111 checkGLcall("glFramebufferRenderbuffer()");
114 if (flags & WINED3D_FBO_ENTRY_FLAG_STENCIL)
116 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb);
117 checkGLcall("glFramebufferRenderbuffer()");
121 static void context_attach_gl_texture_fbo(struct wined3d_context *context,
122 GLenum fbo_target, GLenum attachment, const struct wined3d_fbo_resource *resource)
124 const struct wined3d_gl_info *gl_info = context->gl_info;
126 if (!resource)
128 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, attachment, GL_TEXTURE_2D, 0, 0);
129 checkGLcall("glFramebufferTexture2D()");
131 else if (resource->target == GL_TEXTURE_2D_ARRAY)
133 if (!gl_info->fbo_ops.glFramebufferTextureLayer)
135 FIXME("OpenGL implementation doesn't support glFramebufferTextureLayer().\n");
136 return;
139 gl_info->fbo_ops.glFramebufferTextureLayer(fbo_target, attachment,
140 resource->object, resource->level, resource->layer);
141 checkGLcall("glFramebufferTextureLayer()");
143 else
145 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, attachment,
146 resource->target, resource->object, resource->level);
147 checkGLcall("glFramebufferTexture2D()");
151 /* Context activation is done by the caller. */
152 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
153 GLenum fbo_target, const struct wined3d_fbo_resource *resource, BOOL rb_namespace,
154 DWORD flags)
156 const struct wined3d_gl_info *gl_info = context->gl_info;
158 if (resource->object)
160 TRACE("Attach depth stencil %u.\n", resource->object);
162 if (rb_namespace)
164 context_attach_depth_stencil_rb(gl_info, fbo_target,
165 flags, resource->object);
167 else
169 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
170 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, resource);
172 if (flags & WINED3D_FBO_ENTRY_FLAG_STENCIL)
173 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, resource);
176 if (!(flags & WINED3D_FBO_ENTRY_FLAG_DEPTH))
177 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, NULL);
179 if (!(flags & WINED3D_FBO_ENTRY_FLAG_STENCIL))
180 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, NULL);
182 else
184 TRACE("Attach depth stencil 0.\n");
186 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, NULL);
187 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, NULL);
191 /* Context activation is done by the caller. */
192 static void context_attach_surface_fbo(struct wined3d_context *context,
193 GLenum fbo_target, DWORD idx, const struct wined3d_fbo_resource *resource, BOOL rb_namespace)
195 const struct wined3d_gl_info *gl_info = context->gl_info;
197 TRACE("Attach GL object %u to %u.\n", resource->object, idx);
199 if (resource->object)
202 if (rb_namespace)
204 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
205 GL_RENDERBUFFER, resource->object);
206 checkGLcall("glFramebufferRenderbuffer()");
208 else
210 context_attach_gl_texture_fbo(context, fbo_target, GL_COLOR_ATTACHMENT0 + idx, resource);
213 else
215 context_attach_gl_texture_fbo(context, fbo_target, GL_COLOR_ATTACHMENT0 + idx, NULL);
219 static void context_dump_fbo_attachment(const struct wined3d_gl_info *gl_info, GLenum target,
220 GLenum attachment)
222 static const struct
224 GLenum target;
225 GLenum binding;
226 const char *str;
227 enum wined3d_gl_extension extension;
229 texture_type[] =
231 {GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D, "2d", WINED3D_GL_EXT_NONE},
232 {GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_BINDING_RECTANGLE_ARB, "rectangle", ARB_TEXTURE_RECTANGLE},
233 {GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BINDING_2D_ARRAY, "2d-array", EXT_TEXTURE_ARRAY},
236 GLint type, name, samples, width, height, old_texture, level, face, fmt, tex_target;
238 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
239 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &name);
240 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
241 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);
243 if (type == GL_RENDERBUFFER)
245 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, name);
246 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
247 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
248 if (gl_info->limits.samples > 1)
249 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
250 else
251 samples = 1;
252 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &fmt);
253 FIXME(" %s: renderbuffer %d, %dx%d, %d samples, format %#x.\n",
254 debug_fboattachment(attachment), name, width, height, samples, fmt);
256 else if (type == GL_TEXTURE)
258 const char *tex_type_str;
260 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
261 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &level);
262 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
263 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, &face);
265 if (face)
267 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &old_texture);
269 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, name);
270 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(face, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
271 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(face, level, GL_TEXTURE_WIDTH, &width);
272 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(face, level, GL_TEXTURE_HEIGHT, &height);
274 tex_target = GL_TEXTURE_CUBE_MAP;
275 tex_type_str = "cube";
277 else
279 unsigned int i;
281 tex_type_str = NULL;
282 for (i = 0; i < sizeof(texture_type) / sizeof(*texture_type); ++i)
284 if (!gl_info->supported[texture_type[i].extension])
285 continue;
287 gl_info->gl_ops.gl.p_glGetIntegerv(texture_type[i].binding, &old_texture);
288 while (gl_info->gl_ops.gl.p_glGetError());
290 gl_info->gl_ops.gl.p_glBindTexture(texture_type[i].target, name);
291 if (!gl_info->gl_ops.gl.p_glGetError())
293 tex_target = texture_type[i].target;
294 tex_type_str = texture_type[i].str;
295 break;
297 gl_info->gl_ops.gl.p_glBindTexture(texture_type[i].target, old_texture);
299 if (!tex_type_str)
301 FIXME("Cannot find type of texture %d.\n", name);
302 return;
305 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
306 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_WIDTH, &width);
307 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_HEIGHT, &height);
310 FIXME(" %s: %s texture %d, %dx%d, format %#x.\n", debug_fboattachment(attachment),
311 tex_type_str, name, width, height, fmt);
313 gl_info->gl_ops.gl.p_glBindTexture(tex_target, old_texture);
314 checkGLcall("Guess texture type");
316 else if (type == GL_NONE)
318 FIXME(" %s: NONE.\n", debug_fboattachment(attachment));
320 else
322 ERR(" %s: Unknown attachment %#x.\n", debug_fboattachment(attachment), type);
326 /* Context activation is done by the caller. */
327 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
329 const struct wined3d_gl_info *gl_info = context->gl_info;
330 GLenum status;
332 if (!FIXME_ON(d3d)) return;
334 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
335 if (status == GL_FRAMEBUFFER_COMPLETE)
337 TRACE("FBO complete\n");
339 else
341 unsigned int i;
343 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
345 if (!context->current_fbo)
347 ERR("FBO 0 is incomplete, driver bug?\n");
348 return;
351 context_dump_fbo_attachment(gl_info, target, GL_DEPTH_ATTACHMENT);
352 context_dump_fbo_attachment(gl_info, target, GL_STENCIL_ATTACHMENT);
354 for (i = 0; i < gl_info->limits.buffers; ++i)
355 context_dump_fbo_attachment(gl_info, target, GL_COLOR_ATTACHMENT0 + i);
356 checkGLcall("Dump FBO attachments");
360 static inline DWORD context_generate_rt_mask(GLenum buffer)
362 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
363 return buffer ? (1u << 31) | buffer : 0;
366 static inline DWORD context_generate_rt_mask_from_resource(struct wined3d_resource *resource)
368 if (resource->type != WINED3D_RTYPE_TEXTURE_2D)
370 FIXME("Not implemented for %s resources.\n", debug_d3dresourcetype(resource->type));
371 return 0;
374 return (1u << 31) | wined3d_texture_get_gl_buffer(texture_from_resource(resource));
377 static inline void context_set_fbo_key_for_surface(const struct wined3d_context *context,
378 struct wined3d_fbo_entry_key *key, UINT idx, struct wined3d_surface *surface,
379 DWORD location)
381 if (!surface || surface->container->resource.format->id == WINED3DFMT_NULL)
383 key->objects[idx].object = 0;
384 key->objects[idx].target = 0;
385 key->objects[idx].level = key->objects[idx].layer = 0;
387 else if (surface->current_renderbuffer)
389 key->objects[idx].object = surface->current_renderbuffer->id;
390 key->objects[idx].target = 0;
391 key->objects[idx].level = key->objects[idx].layer = 0;
392 key->rb_namespace |= 1 << idx;
394 else
396 switch (location)
398 case WINED3D_LOCATION_TEXTURE_RGB:
399 key->objects[idx].object = surface_get_texture_name(surface, context, FALSE);
400 key->objects[idx].target = surface->texture_target;
401 key->objects[idx].level = surface->texture_level;
402 key->objects[idx].layer = surface->texture_layer;
403 break;
405 case WINED3D_LOCATION_TEXTURE_SRGB:
406 key->objects[idx].object = surface_get_texture_name(surface, context, TRUE);
407 key->objects[idx].target = surface->texture_target;
408 key->objects[idx].level = surface->texture_level;
409 key->objects[idx].layer = surface->texture_layer;
410 break;
412 case WINED3D_LOCATION_RB_MULTISAMPLE:
413 key->objects[idx].object = surface->container->rb_multisample;
414 key->objects[idx].target = 0;
415 key->objects[idx].level = key->objects[idx].layer = 0;
416 key->rb_namespace |= 1 << idx;
417 break;
419 case WINED3D_LOCATION_RB_RESOLVED:
420 key->objects[idx].object = surface->container->rb_resolved;
421 key->objects[idx].target = 0;
422 key->objects[idx].level = key->objects[idx].layer = 0;
423 key->rb_namespace |= 1 << idx;
424 break;
429 static void context_generate_fbo_key(const struct wined3d_context *context,
430 struct wined3d_fbo_entry_key *key, struct wined3d_surface **render_targets,
431 struct wined3d_surface *depth_stencil, DWORD color_location,
432 DWORD ds_location)
434 UINT i;
436 key->rb_namespace = 0;
437 context_set_fbo_key_for_surface(context, key, 0, depth_stencil, ds_location);
439 for (i = 0; i < context->gl_info->limits.buffers; ++i)
440 context_set_fbo_key_for_surface(context, key, i + 1, render_targets[i], color_location);
443 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
444 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
445 DWORD color_location, DWORD ds_location)
447 const struct wined3d_gl_info *gl_info = context->gl_info;
448 struct fbo_entry *entry;
449 UINT object_count = gl_info->limits.buffers + 1;
451 entry = HeapAlloc(GetProcessHeap(), 0,
452 FIELD_OFFSET(struct fbo_entry, key.objects[object_count]));
453 memset(&entry->key, 0, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count]));
454 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
455 entry->flags = 0;
456 if (depth_stencil)
458 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
459 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
460 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
461 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
463 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
464 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
465 checkGLcall("glGenFramebuffers()");
466 TRACE("Created FBO %u.\n", entry->id);
468 return entry;
471 /* Context activation is done by the caller. */
472 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
473 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
474 DWORD color_location, DWORD ds_location, struct fbo_entry *entry)
476 const struct wined3d_gl_info *gl_info = context->gl_info;
478 context_bind_fbo(context, target, entry->id);
479 context_clean_fbo_attachments(gl_info, target);
481 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
482 entry->flags = 0;
483 if (depth_stencil)
485 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
486 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
487 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
488 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
492 /* Context activation is done by the caller. */
493 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
495 if (entry->id)
497 TRACE("Destroy FBO %u.\n", entry->id);
498 context_destroy_fbo(context, entry->id);
500 --context->fbo_entry_count;
501 list_remove(&entry->entry);
502 HeapFree(GetProcessHeap(), 0, entry);
505 /* Context activation is done by the caller. */
506 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
507 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
508 DWORD color_location, DWORD ds_location)
510 const struct wined3d_gl_info *gl_info = context->gl_info;
511 unsigned int object_count = gl_info->limits.buffers + 1;
512 struct wined3d_texture *rt_texture, *ds_texture;
513 struct fbo_entry *entry;
514 unsigned int i;
516 if (depth_stencil && render_targets[0])
518 rt_texture = render_targets[0]->container;
519 ds_texture = depth_stencil->container;
521 if (wined3d_texture_get_level_width(ds_texture, depth_stencil->texture_level)
522 < wined3d_texture_get_level_width(rt_texture, render_targets[0]->texture_level)
523 || wined3d_texture_get_level_height(ds_texture, depth_stencil->texture_level)
524 < wined3d_texture_get_level_height(rt_texture, render_targets[0]->texture_level))
526 WARN("Depth stencil is smaller than the primary color buffer, disabling.\n");
527 depth_stencil = NULL;
529 else if (ds_texture->resource.multisample_type != rt_texture->resource.multisample_type
530 || ds_texture->resource.multisample_quality != rt_texture->resource.multisample_quality)
532 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
533 rt_texture->resource.multisample_type, rt_texture->resource.multisample_quality,
534 ds_texture->resource.multisample_type, ds_texture->resource.multisample_quality);
535 depth_stencil = NULL;
537 else
538 surface_set_compatible_renderbuffer(depth_stencil, render_targets[0]);
541 context_generate_fbo_key(context, context->fbo_key, render_targets, depth_stencil, color_location,
542 ds_location);
544 if (TRACE_ON(d3d))
546 TRACE("Dumping FBO attachments:\n");
547 for (i = 0; i < gl_info->limits.buffers; ++i)
549 if (render_targets[i])
551 rt_texture = render_targets[i]->container;
552 TRACE(" Color attachment %u: %p format %s, %s %u, %ux%u, %u samples.\n",
553 i, render_targets[i], debug_d3dformat(rt_texture->resource.format->id),
554 context->fbo_key->rb_namespace & (1 << (i + 1)) ? "renderbuffer" : "texture",
555 context->fbo_key->objects[i + 1].object,
556 wined3d_texture_get_level_pow2_width(rt_texture, render_targets[i]->texture_level),
557 wined3d_texture_get_level_pow2_height(rt_texture, render_targets[i]->texture_level),
558 rt_texture->resource.multisample_type);
561 if (depth_stencil)
563 ds_texture = depth_stencil->container;
564 TRACE(" Depth attachment: %p format %s, %s %u, %ux%u, %u samples.\n",
565 depth_stencil, debug_d3dformat(ds_texture->resource.format->id),
566 context->fbo_key->rb_namespace & (1 << 0) ? "renderbuffer" : "texture",
567 context->fbo_key->objects[0].object,
568 wined3d_texture_get_level_pow2_width(ds_texture, depth_stencil->texture_level),
569 wined3d_texture_get_level_pow2_height(ds_texture, depth_stencil->texture_level),
570 ds_texture->resource.multisample_type);
574 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
576 if (memcmp(context->fbo_key, &entry->key, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count])))
577 continue;
579 list_remove(&entry->entry);
580 list_add_head(&context->fbo_list, &entry->entry);
581 return entry;
584 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
586 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
587 list_add_head(&context->fbo_list, &entry->entry);
588 ++context->fbo_entry_count;
590 else
592 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
593 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
594 list_remove(&entry->entry);
595 list_add_head(&context->fbo_list, &entry->entry);
598 return entry;
601 /* Context activation is done by the caller. */
602 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
604 const struct wined3d_gl_info *gl_info = context->gl_info;
605 unsigned int i;
606 GLuint read_binding, draw_binding;
608 if (entry->flags & WINED3D_FBO_ENTRY_FLAG_ATTACHED)
610 context_bind_fbo(context, target, entry->id);
611 return;
614 read_binding = context->fbo_read_binding;
615 draw_binding = context->fbo_draw_binding;
616 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
618 /* Apply render targets */
619 for (i = 0; i < gl_info->limits.buffers; ++i)
621 context_attach_surface_fbo(context, target, i, &entry->key.objects[i + 1],
622 entry->key.rb_namespace & (1 << (i + 1)));
625 context_attach_depth_stencil_fbo(context, target, &entry->key.objects[0],
626 entry->key.rb_namespace & 0x1, entry->flags);
628 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
629 * GL contexts requirements. */
630 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
631 context_set_draw_buffer(context, GL_NONE);
632 if (target != GL_FRAMEBUFFER)
634 if (target == GL_READ_FRAMEBUFFER)
635 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
636 else
637 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
640 entry->flags |= WINED3D_FBO_ENTRY_FLAG_ATTACHED;
643 /* Context activation is done by the caller. */
644 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
645 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
646 DWORD color_location, DWORD ds_location)
648 struct fbo_entry *entry, *entry2;
650 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
652 context_destroy_fbo_entry(context, entry);
655 if (context->rebind_fbo)
657 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
658 context->rebind_fbo = FALSE;
661 if (color_location == WINED3D_LOCATION_DRAWABLE)
663 context->current_fbo = NULL;
664 context_bind_fbo(context, target, 0);
666 else
668 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
669 color_location, ds_location);
670 context_apply_fbo_entry(context, target, context->current_fbo);
674 /* Context activation is done by the caller. */
675 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
676 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
678 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
680 context->blit_targets[0] = render_target;
681 if (clear_size)
682 memset(&context->blit_targets[1], 0, clear_size);
683 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
686 /* Context activation is done by the caller. */
687 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
689 const struct wined3d_gl_info *gl_info = context->gl_info;
691 if (context->free_occlusion_query_count)
693 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
695 else
697 if (gl_info->supported[ARB_OCCLUSION_QUERY])
699 GL_EXTCALL(glGenQueries(1, &query->id));
700 checkGLcall("glGenQueries");
702 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
704 else
706 WARN("Occlusion queries not supported, not allocating query id.\n");
707 query->id = 0;
711 query->context = context;
712 list_add_head(&context->occlusion_queries, &query->entry);
715 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
717 struct wined3d_context *context = query->context;
719 list_remove(&query->entry);
720 query->context = NULL;
722 if (!wined3d_array_reserve((void **)&context->free_occlusion_queries,
723 &context->free_occlusion_query_size, context->free_occlusion_query_count + 1,
724 sizeof(*context->free_occlusion_queries)))
726 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
727 return;
730 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
733 /* Context activation is done by the caller. */
734 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
736 const struct wined3d_gl_info *gl_info = context->gl_info;
738 if (context->free_event_query_count)
740 query->object = context->free_event_queries[--context->free_event_query_count];
742 else
744 if (gl_info->supported[ARB_SYNC])
746 /* Using ARB_sync, not much to do here. */
747 query->object.sync = NULL;
748 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
750 else if (gl_info->supported[APPLE_FENCE])
752 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
753 checkGLcall("glGenFencesAPPLE");
755 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
757 else if(gl_info->supported[NV_FENCE])
759 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
760 checkGLcall("glGenFencesNV");
762 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
764 else
766 WARN("Event queries not supported, not allocating query id.\n");
767 query->object.id = 0;
771 query->context = context;
772 list_add_head(&context->event_queries, &query->entry);
775 void context_free_event_query(struct wined3d_event_query *query)
777 struct wined3d_context *context = query->context;
779 list_remove(&query->entry);
780 query->context = NULL;
782 if (!wined3d_array_reserve((void **)&context->free_event_queries,
783 &context->free_event_query_size, context->free_event_query_count + 1,
784 sizeof(*context->free_event_queries)))
786 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
787 return;
790 context->free_event_queries[context->free_event_query_count++] = query->object;
793 /* Context activation is done by the caller. */
794 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
796 const struct wined3d_gl_info *gl_info = context->gl_info;
798 if (context->free_timestamp_query_count)
800 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
802 else
804 GL_EXTCALL(glGenQueries(1, &query->id));
805 checkGLcall("glGenQueries");
807 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
810 query->context = context;
811 list_add_head(&context->timestamp_queries, &query->entry);
814 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
816 struct wined3d_context *context = query->context;
818 list_remove(&query->entry);
819 query->context = NULL;
821 if (!wined3d_array_reserve((void **)&context->free_timestamp_queries,
822 &context->free_timestamp_query_size, context->free_timestamp_query_count + 1,
823 sizeof(*context->free_timestamp_queries)))
825 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
826 return;
829 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
832 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
834 static void context_enum_fbo_entries(const struct wined3d_device *device,
835 GLuint name, BOOL rb_namespace, context_fbo_entry_func_t *callback)
837 UINT i;
839 for (i = 0; i < device->context_count; ++i)
841 struct wined3d_context *context = device->contexts[i];
842 const struct wined3d_gl_info *gl_info = context->gl_info;
843 struct fbo_entry *entry, *entry2;
845 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
847 UINT j;
849 for (j = 0; j < gl_info->limits.buffers + 1; ++j)
851 if (entry->key.objects[j].object == name
852 && !(entry->key.rb_namespace & (1 << j)) == !rb_namespace)
854 callback(context, entry);
855 break;
862 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
864 list_remove(&entry->entry);
865 list_add_head(&context->fbo_destroy_list, &entry->entry);
868 void context_resource_released(const struct wined3d_device *device,
869 struct wined3d_resource *resource, enum wined3d_resource_type type)
871 struct wined3d_texture *texture;
872 UINT i;
874 if (!device->d3d_initialized)
875 return;
877 switch (type)
879 case WINED3D_RTYPE_TEXTURE_2D:
880 case WINED3D_RTYPE_TEXTURE_3D:
881 texture = texture_from_resource(resource);
883 for (i = 0; i < device->context_count; ++i)
885 struct wined3d_context *context = device->contexts[i];
886 if (context->current_rt.texture == texture)
888 context->current_rt.texture = NULL;
889 context->current_rt.sub_resource_idx = 0;
892 break;
894 default:
895 break;
899 void context_gl_resource_released(struct wined3d_device *device,
900 GLuint name, BOOL rb_namespace)
902 context_enum_fbo_entries(device, name, rb_namespace, context_queue_fbo_entry_destruction);
905 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
907 const struct wined3d_gl_info *gl_info = context->gl_info;
908 struct fbo_entry *entry = context->current_fbo;
909 unsigned int i;
911 if (!entry || context->rebind_fbo) return;
913 for (i = 0; i < gl_info->limits.buffers + 1; ++i)
915 if (surface->container->texture_rgb.name == entry->key.objects[i].object
916 || surface->container->texture_srgb.name == entry->key.objects[i].object)
918 TRACE("Updated surface %p is bound as attachment %u to the current FBO.\n", surface, i);
919 context->rebind_fbo = TRUE;
920 return;
925 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
927 const struct wined3d_gl_info *gl_info = ctx->gl_info;
928 BOOL ret = FALSE;
930 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
932 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
934 HDC dc = GetDCEx(ctx->restore_pf_win, 0, DCX_USESTYLE | DCX_CACHE);
935 if (dc)
937 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
939 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
940 ctx->restore_pf, ctx->restore_pf_win);
942 ReleaseDC(ctx->restore_pf_win, dc);
945 else
947 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
951 ctx->restore_pf = 0;
952 ctx->restore_pf_win = NULL;
953 return ret;
956 static BOOL context_set_pixel_format(struct wined3d_context *context, HDC dc, BOOL private, int format)
958 const struct wined3d_gl_info *gl_info = context->gl_info;
959 int current;
961 if (dc == context->hdc && context->hdc_is_private && context->hdc_has_format)
962 return TRUE;
964 current = gl_info->gl_ops.wgl.p_wglGetPixelFormat(dc);
965 if (current == format) goto success;
967 if (!current)
969 if (!SetPixelFormat(dc, format, NULL))
971 /* This may also happen if the dc belongs to a destroyed window. */
972 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
973 format, dc, GetLastError());
974 return FALSE;
977 context->restore_pf = 0;
978 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
979 goto success;
982 /* By default WGL doesn't allow pixel format adjustments but we need it
983 * here. For this reason there's a Wine specific wglSetPixelFormat()
984 * which allows us to set the pixel format multiple times. Only use it
985 * when really needed. */
986 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
988 HWND win;
990 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
992 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
993 format, dc);
994 return FALSE;
997 win = private ? NULL : WindowFromDC(dc);
998 if (win != context->restore_pf_win)
1000 context_restore_pixel_format(context);
1002 context->restore_pf = private ? 0 : current;
1003 context->restore_pf_win = win;
1006 goto success;
1009 /* OpenGL doesn't allow pixel format adjustments. Print an error and
1010 * continue using the old format. There's a big chance that the old
1011 * format works although with a performance hit and perhaps rendering
1012 * errors. */
1013 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
1014 format, dc, current);
1015 return TRUE;
1017 success:
1018 if (dc == context->hdc && context->hdc_is_private)
1019 context->hdc_has_format = TRUE;
1020 return TRUE;
1023 static BOOL context_set_gl_context(struct wined3d_context *ctx)
1025 struct wined3d_swapchain *swapchain = ctx->swapchain;
1026 BOOL backup = FALSE;
1028 if (!context_set_pixel_format(ctx, ctx->hdc, ctx->hdc_is_private, ctx->pixel_format))
1030 WARN("Failed to set pixel format %d on device context %p.\n",
1031 ctx->pixel_format, ctx->hdc);
1032 backup = TRUE;
1035 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
1037 HDC dc;
1039 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
1040 ctx->glCtx, ctx->hdc, GetLastError());
1041 ctx->valid = 0;
1042 WARN("Trying fallback to the backup window.\n");
1044 /* FIXME: If the context is destroyed it's no longer associated with
1045 * a swapchain, so we can't use the swapchain to get a backup dc. To
1046 * make this work windowless contexts would need to be handled by the
1047 * device. */
1048 if (ctx->destroyed || !swapchain)
1050 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
1051 context_set_current(NULL);
1052 return FALSE;
1055 if (!(dc = swapchain_get_backup_dc(swapchain)))
1057 context_set_current(NULL);
1058 return FALSE;
1061 if (!context_set_pixel_format(ctx, dc, TRUE, ctx->pixel_format))
1063 ERR("Failed to set pixel format %d on device context %p.\n",
1064 ctx->pixel_format, dc);
1065 context_set_current(NULL);
1066 return FALSE;
1069 if (!wglMakeCurrent(dc, ctx->glCtx))
1071 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
1072 dc, GetLastError());
1073 context_set_current(NULL);
1074 return FALSE;
1077 ctx->valid = 1;
1079 ctx->needs_set = 0;
1080 return TRUE;
1083 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
1085 if (!wglMakeCurrent(dc, gl_ctx))
1087 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1088 gl_ctx, dc, GetLastError());
1089 context_set_current(NULL);
1093 static void context_update_window(struct wined3d_context *context)
1095 if (!context->swapchain)
1096 return;
1098 if (context->win_handle == context->swapchain->win_handle)
1099 return;
1101 TRACE("Updating context %p window from %p to %p.\n",
1102 context, context->win_handle, context->swapchain->win_handle);
1104 if (context->hdc)
1105 wined3d_release_dc(context->win_handle, context->hdc);
1107 context->win_handle = context->swapchain->win_handle;
1108 context->hdc_is_private = FALSE;
1109 context->hdc_has_format = FALSE;
1110 context->needs_set = 1;
1111 context->valid = 1;
1113 if (!(context->hdc = GetDCEx(context->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1115 ERR("Failed to get a device context for window %p.\n", context->win_handle);
1116 context->valid = 0;
1120 static void context_destroy_gl_resources(struct wined3d_context *context)
1122 const struct wined3d_gl_info *gl_info = context->gl_info;
1123 struct wined3d_timestamp_query *timestamp_query;
1124 struct wined3d_occlusion_query *occlusion_query;
1125 struct wined3d_event_query *event_query;
1126 struct fbo_entry *entry, *entry2;
1127 HGLRC restore_ctx;
1128 HDC restore_dc;
1129 unsigned int i;
1131 restore_ctx = wglGetCurrentContext();
1132 restore_dc = wglGetCurrentDC();
1134 if (restore_ctx == context->glCtx)
1135 restore_ctx = NULL;
1136 else if (context->valid)
1137 context_set_gl_context(context);
1139 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
1141 if (context->valid)
1142 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
1143 timestamp_query->context = NULL;
1146 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1148 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1149 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1150 occlusion_query->context = NULL;
1153 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
1155 if (context->valid)
1157 if (gl_info->supported[ARB_SYNC])
1159 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
1161 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
1162 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
1164 event_query->context = NULL;
1167 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1169 if (!context->valid) entry->id = 0;
1170 context_destroy_fbo_entry(context, entry);
1173 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1175 if (!context->valid) entry->id = 0;
1176 context_destroy_fbo_entry(context, entry);
1179 if (context->valid)
1181 if (context->dummy_arbfp_prog)
1183 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1186 if (gl_info->supported[ARB_TIMER_QUERY])
1187 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1189 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1190 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1192 if (gl_info->supported[ARB_SYNC])
1194 for (i = 0; i < context->free_event_query_count; ++i)
1196 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
1199 else if (gl_info->supported[APPLE_FENCE])
1201 for (i = 0; i < context->free_event_query_count; ++i)
1203 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1206 else if (gl_info->supported[NV_FENCE])
1208 for (i = 0; i < context->free_event_query_count; ++i)
1210 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1214 checkGLcall("context cleanup");
1217 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1218 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1219 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1221 context_restore_pixel_format(context);
1222 if (restore_ctx)
1224 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1226 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1228 ERR("Failed to disable GL context.\n");
1231 wined3d_release_dc(context->win_handle, context->hdc);
1233 if (!wglDeleteContext(context->glCtx))
1235 DWORD err = GetLastError();
1236 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1240 DWORD context_get_tls_idx(void)
1242 return wined3d_context_tls_idx;
1245 void context_set_tls_idx(DWORD idx)
1247 wined3d_context_tls_idx = idx;
1250 struct wined3d_context *context_get_current(void)
1252 return TlsGetValue(wined3d_context_tls_idx);
1255 BOOL context_set_current(struct wined3d_context *ctx)
1257 struct wined3d_context *old = context_get_current();
1259 if (old == ctx)
1261 TRACE("Already using D3D context %p.\n", ctx);
1262 return TRUE;
1265 if (old)
1267 if (old->destroyed)
1269 TRACE("Switching away from destroyed context %p.\n", old);
1270 context_destroy_gl_resources(old);
1271 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1272 HeapFree(GetProcessHeap(), 0, old);
1274 else
1276 if (wglGetCurrentContext())
1278 const struct wined3d_gl_info *gl_info = old->gl_info;
1279 TRACE("Flushing context %p before switching to %p.\n", old, ctx);
1280 gl_info->gl_ops.gl.p_glFlush();
1282 old->current = 0;
1286 if (ctx)
1288 if (!ctx->valid)
1290 ERR("Trying to make invalid context %p current\n", ctx);
1291 return FALSE;
1294 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1295 if (!context_set_gl_context(ctx))
1296 return FALSE;
1297 ctx->current = 1;
1299 else if (wglGetCurrentContext())
1301 TRACE("Clearing current D3D context.\n");
1302 if (!wglMakeCurrent(NULL, NULL))
1304 DWORD err = GetLastError();
1305 ERR("Failed to clear current GL context, last error %#x.\n", err);
1306 TlsSetValue(wined3d_context_tls_idx, NULL);
1307 return FALSE;
1311 return TlsSetValue(wined3d_context_tls_idx, ctx);
1314 void context_release(struct wined3d_context *context)
1316 TRACE("Releasing context %p, level %u.\n", context, context->level);
1318 if (WARN_ON(d3d))
1320 if (!context->level)
1321 WARN("Context %p is not active.\n", context);
1322 else if (context != context_get_current())
1323 WARN("Context %p is not the current context.\n", context);
1326 if (!--context->level)
1328 if (context_restore_pixel_format(context))
1329 context->needs_set = 1;
1330 if (context->restore_ctx)
1332 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1333 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1334 context->restore_ctx = NULL;
1335 context->restore_dc = NULL;
1338 if (context->destroy_delayed)
1340 TRACE("Destroying context %p.\n", context);
1341 context_destroy(context->device, context);
1346 /* This is used when a context for render target A is active, but a separate context is
1347 * needed to access the WGL framebuffer for render target B. Re-acquire a context for rt
1348 * A to avoid breaking caller code. */
1349 void context_restore(struct wined3d_context *context, struct wined3d_surface *restore)
1351 if (context->current_rt.texture != restore->container
1352 || context->current_rt.sub_resource_idx != surface_get_sub_resource_idx(restore))
1354 context_release(context);
1355 context = context_acquire(restore->container->resource.device,
1356 restore->container, surface_get_sub_resource_idx(restore));
1359 context_release(context);
1362 static void context_enter(struct wined3d_context *context)
1364 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1366 if (!context->level++)
1368 const struct wined3d_context *current_context = context_get_current();
1369 HGLRC current_gl = wglGetCurrentContext();
1371 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1373 TRACE("Another GL context (%p on device context %p) is already current.\n",
1374 current_gl, wglGetCurrentDC());
1375 context->restore_ctx = current_gl;
1376 context->restore_dc = wglGetCurrentDC();
1377 context->needs_set = 1;
1379 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1380 && context->pixel_format != context->gl_info->gl_ops.wgl.p_wglGetPixelFormat(context->hdc))
1381 context->needs_set = 1;
1385 void context_invalidate_compute_state(struct wined3d_context *context, DWORD state_id)
1387 DWORD representative = context->state_table[state_id].representative - STATE_COMPUTE_OFFSET;
1388 unsigned int index, shift;
1390 index = representative / (sizeof(*context->dirty_compute_states) * CHAR_BIT);
1391 shift = representative & (sizeof(*context->dirty_compute_states) * CHAR_BIT - 1);
1392 context->dirty_compute_states[index] |= (1u << shift);
1395 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1397 DWORD rep = context->state_table[state].representative;
1398 DWORD idx;
1399 BYTE shift;
1401 if (isStateDirty(context, rep)) return;
1403 context->dirtyArray[context->numDirtyEntries++] = rep;
1404 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1405 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1406 context->isStateDirty[idx] |= (1u << shift);
1409 /* This function takes care of wined3d pixel format selection. */
1410 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1411 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1412 BOOL auxBuffers)
1414 unsigned int cfg_count = device->adapter->cfg_count;
1415 unsigned int current_value;
1416 PIXELFORMATDESCRIPTOR pfd;
1417 int iPixelFormat = 0;
1418 unsigned int i;
1420 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x.\n",
1421 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1422 auxBuffers);
1424 current_value = 0;
1425 for (i = 0; i < cfg_count; ++i)
1427 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1428 unsigned int value;
1430 /* For now only accept RGBA formats. Perhaps some day we will
1431 * allow floating point formats for pbuffers. */
1432 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1433 continue;
1434 /* In window mode we need a window drawable format and double buffering. */
1435 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1436 continue;
1437 if (cfg->redSize < color_format->red_size)
1438 continue;
1439 if (cfg->greenSize < color_format->green_size)
1440 continue;
1441 if (cfg->blueSize < color_format->blue_size)
1442 continue;
1443 if (cfg->alphaSize < color_format->alpha_size)
1444 continue;
1445 if (cfg->depthSize < ds_format->depth_size)
1446 continue;
1447 if (ds_format->stencil_size && cfg->stencilSize != ds_format->stencil_size)
1448 continue;
1449 /* Check multisampling support. */
1450 if (cfg->numSamples)
1451 continue;
1453 value = 1;
1454 /* We try to locate a format which matches our requirements exactly. In case of
1455 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1456 if (cfg->depthSize == ds_format->depth_size)
1457 value += 1;
1458 if (cfg->stencilSize == ds_format->stencil_size)
1459 value += 2;
1460 if (cfg->alphaSize == color_format->alpha_size)
1461 value += 4;
1462 /* We like to have aux buffers in backbuffer mode */
1463 if (auxBuffers && cfg->auxBuffers)
1464 value += 8;
1465 if (cfg->redSize == color_format->red_size
1466 && cfg->greenSize == color_format->green_size
1467 && cfg->blueSize == color_format->blue_size)
1468 value += 16;
1470 if (value > current_value)
1472 iPixelFormat = cfg->iPixelFormat;
1473 current_value = value;
1477 if (!iPixelFormat)
1479 ERR("Trying to locate a compatible pixel format because an exact match failed.\n");
1481 memset(&pfd, 0, sizeof(pfd));
1482 pfd.nSize = sizeof(pfd);
1483 pfd.nVersion = 1;
1484 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1485 pfd.iPixelType = PFD_TYPE_RGBA;
1486 pfd.cAlphaBits = color_format->alpha_size;
1487 pfd.cColorBits = color_format->red_size + color_format->green_size
1488 + color_format->blue_size + color_format->alpha_size;
1489 pfd.cDepthBits = ds_format->depth_size;
1490 pfd.cStencilBits = ds_format->stencil_size;
1491 pfd.iLayerType = PFD_MAIN_PLANE;
1493 if (!(iPixelFormat = ChoosePixelFormat(hdc, &pfd)))
1495 /* Something is very wrong as ChoosePixelFormat() barely fails. */
1496 ERR("Can't find a suitable pixel format.\n");
1497 return 0;
1501 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s.\n",
1502 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1503 return iPixelFormat;
1506 /* Context activation is done by the caller. */
1507 void context_bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1509 const struct wined3d_gl_info *gl_info = context->gl_info;
1510 unsigned int i;
1512 for (i = 0; i < gl_info->limits.combined_samplers; ++i)
1514 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1515 checkGLcall("glActiveTexture");
1517 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_textures.tex_2d);
1519 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1520 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_textures.tex_rect);
1522 if (gl_info->supported[EXT_TEXTURE3D])
1523 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_textures.tex_3d);
1525 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1526 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_textures.tex_cube);
1528 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP_ARRAY])
1529 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, device->dummy_textures.tex_cube_array);
1531 if (gl_info->supported[EXT_TEXTURE_ARRAY])
1532 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, device->dummy_textures.tex_2d_array);
1534 if (gl_info->supported[ARB_TEXTURE_BUFFER_OBJECT])
1535 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_BUFFER, device->dummy_textures.tex_buffer);
1537 checkGLcall("Bind dummy textures");
1541 void wined3d_check_gl_call(const struct wined3d_gl_info *gl_info,
1542 const char *file, unsigned int line, const char *name)
1544 GLint err;
1546 if (gl_info->supported[ARB_DEBUG_OUTPUT] || (err = gl_info->gl_ops.gl.p_glGetError()) == GL_NO_ERROR)
1548 TRACE("%s call ok %s / %u.\n", name, file, line);
1549 return;
1554 ERR(">>>>>>> %s (%#x) from %s @ %s / %u.\n",
1555 debug_glerror(err), err, name, file,line);
1556 err = gl_info->gl_ops.gl.p_glGetError();
1557 } while (err != GL_NO_ERROR);
1560 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1562 return gl_info->supported[ARB_DEBUG_OUTPUT]
1563 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1566 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1567 GLenum severity, GLsizei length, const char *message, void *ctx)
1569 switch (type)
1571 case GL_DEBUG_TYPE_ERROR_ARB:
1572 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1573 break;
1575 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1576 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1577 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1578 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1579 break;
1581 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1582 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1583 break;
1585 default:
1586 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1587 break;
1591 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1593 HGLRC ctx;
1594 unsigned int ctx_attrib_idx = 0;
1595 GLint ctx_attribs[7], ctx_flags = 0;
1597 if (context_debug_output_enabled(gl_info))
1598 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1599 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1600 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1601 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1602 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1603 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1604 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1605 if (ctx_flags)
1607 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1608 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1610 ctx_attribs[ctx_attrib_idx] = 0;
1612 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1614 if (ctx_flags & WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
1616 ctx_attribs[ctx_attrib_idx - 1] &= ~WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1617 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1618 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1619 GetLastError());
1622 return ctx;
1625 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1626 struct wined3d_texture *target, const struct wined3d_format *ds_format)
1628 struct wined3d_device *device = swapchain->device;
1629 const struct wined3d_d3d_info *d3d_info = &device->adapter->d3d_info;
1630 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1631 const struct wined3d_format *color_format;
1632 struct wined3d_context *ret;
1633 BOOL hdc_is_private = FALSE;
1634 BOOL auxBuffers = FALSE;
1635 HGLRC ctx, share_ctx;
1636 DWORD target_usage;
1637 int pixel_format;
1638 unsigned int i;
1639 DWORD state;
1640 HDC hdc = 0;
1642 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1644 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1645 if (!ret)
1646 return NULL;
1648 if (!(ret->blit_targets = wined3d_calloc(gl_info->limits.buffers, sizeof(*ret->blit_targets))))
1649 goto out;
1651 if (!(ret->draw_buffers = wined3d_calloc(gl_info->limits.buffers, sizeof(*ret->draw_buffers))))
1652 goto out;
1654 ret->fbo_key = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1655 FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[gl_info->limits.buffers + 1]));
1656 if (!ret->fbo_key)
1657 goto out;
1659 ret->free_timestamp_query_size = 4;
1660 if (!(ret->free_timestamp_queries = wined3d_calloc(ret->free_timestamp_query_size,
1661 sizeof(*ret->free_timestamp_queries))))
1662 goto out;
1663 list_init(&ret->timestamp_queries);
1665 ret->free_occlusion_query_size = 4;
1666 if (!(ret->free_occlusion_queries = wined3d_calloc(ret->free_occlusion_query_size,
1667 sizeof(*ret->free_occlusion_queries))))
1668 goto out;
1670 list_init(&ret->occlusion_queries);
1672 ret->free_event_query_size = 4;
1673 if (!(ret->free_event_queries = wined3d_calloc(ret->free_event_query_size,
1674 sizeof(*ret->free_event_queries))))
1675 goto out;
1677 list_init(&ret->event_queries);
1678 list_init(&ret->fbo_list);
1679 list_init(&ret->fbo_destroy_list);
1681 if (!device->shader_backend->shader_allocate_context_data(ret))
1683 ERR("Failed to allocate shader backend context data.\n");
1684 goto out;
1686 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1688 ERR("Failed to allocate fragment pipeline context data.\n");
1689 goto out;
1692 for (i = 0; i < ARRAY_SIZE(ret->tex_unit_map); ++i)
1693 ret->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
1694 for (i = 0; i < ARRAY_SIZE(ret->rev_tex_unit_map); ++i)
1695 ret->rev_tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
1696 if (gl_info->limits.graphics_samplers >= MAX_COMBINED_SAMPLERS)
1698 /* Initialize the texture unit mapping to a 1:1 mapping. */
1699 unsigned int base, count;
1701 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, WINED3D_SHADER_TYPE_PIXEL, &base, &count);
1702 if (base + MAX_FRAGMENT_SAMPLERS > ARRAY_SIZE(ret->rev_tex_unit_map))
1704 ERR("Unexpected texture unit base index %u.\n", base);
1705 goto out;
1707 for (i = 0; i < min(count, MAX_FRAGMENT_SAMPLERS); ++i)
1709 ret->tex_unit_map[i] = base + i;
1710 ret->rev_tex_unit_map[base + i] = i;
1713 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, WINED3D_SHADER_TYPE_VERTEX, &base, &count);
1714 if (base + MAX_VERTEX_SAMPLERS > ARRAY_SIZE(ret->rev_tex_unit_map))
1716 ERR("Unexpected texture unit base index %u.\n", base);
1717 goto out;
1719 for (i = 0; i < min(count, MAX_VERTEX_SAMPLERS); ++i)
1721 ret->tex_unit_map[MAX_FRAGMENT_SAMPLERS + i] = base + i;
1722 ret->rev_tex_unit_map[base + i] = MAX_FRAGMENT_SAMPLERS + i;
1726 if (!(ret->texture_type = wined3d_calloc(gl_info->limits.combined_samplers,
1727 sizeof(*ret->texture_type))))
1728 goto out;
1730 if (!(hdc = GetDCEx(swapchain->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1732 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1734 if ((hdc = swapchain_get_backup_dc(swapchain)))
1735 hdc_is_private = TRUE;
1736 else
1738 ERR("Failed to retrieve a device context.\n");
1739 goto out;
1743 color_format = target->resource.format;
1744 target_usage = target->resource.usage;
1746 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1747 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1748 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1750 auxBuffers = TRUE;
1752 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1753 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM, target_usage);
1754 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1755 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1758 /* DirectDraw supports 8bit paletted render targets and these are used by
1759 * old games like StarCraft and C&C. Most modern hardware doesn't support
1760 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1761 * conversion (ab)uses the alpha component for storing the palette index.
1762 * For this reason we require a format with 8bit alpha, so request
1763 * A8R8G8B8. */
1764 if (color_format->id == WINED3DFMT_P8_UINT)
1765 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1767 /* When using FBOs for off-screen rendering, we only use the drawable for
1768 * presentation blits, and don't do any rendering to it. That means we
1769 * don't need depth or stencil buffers, and can mostly ignore the render
1770 * target format. This wouldn't necessarily be quite correct for 10bpc
1771 * display modes, but we don't currently support those.
1772 * Using the same format regardless of the color/depth/stencil targets
1773 * makes it much less likely that different wined3d instances will set
1774 * conflicting pixel formats. */
1775 if (wined3d_settings.offscreen_rendering_mode != ORM_BACKBUFFER)
1777 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1778 ds_format = wined3d_get_format(gl_info, WINED3DFMT_UNKNOWN, WINED3DUSAGE_DEPTHSTENCIL);
1781 /* Try to find a pixel format which matches our requirements. */
1782 if (!(pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers)))
1783 goto out;
1785 ret->gl_info = gl_info;
1787 context_enter(ret);
1789 if (!context_set_pixel_format(ret, hdc, hdc_is_private, pixel_format))
1791 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1792 context_release(ret);
1793 goto out;
1796 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1797 if (gl_info->p_wglCreateContextAttribsARB)
1799 if (!(ctx = context_create_wgl_attribs(gl_info, hdc, share_ctx)))
1800 goto out;
1802 else
1804 if (!(ctx = wglCreateContext(hdc)))
1806 ERR("Failed to create a WGL context.\n");
1807 context_release(ret);
1808 goto out;
1811 if (share_ctx && !wglShareLists(share_ctx, ctx))
1813 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1814 context_release(ret);
1815 if (!wglDeleteContext(ctx))
1816 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1817 goto out;
1821 if (!device_context_add(device, ret))
1823 ERR("Failed to add the newly created context to the context list\n");
1824 context_release(ret);
1825 if (!wglDeleteContext(ctx))
1826 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1827 goto out;
1830 ret->d3d_info = d3d_info;
1831 ret->state_table = device->StateTable;
1833 /* Mark all states dirty to force a proper initialization of the states on
1834 * the first use of the context. Compute states do not need initialization. */
1835 for (state = 0; state <= STATE_HIGHEST; ++state)
1837 if (ret->state_table[state].representative && !STATE_IS_COMPUTE(state))
1838 context_invalidate_state(ret, state);
1841 ret->device = device;
1842 ret->swapchain = swapchain;
1843 ret->current_rt.texture = target;
1844 ret->current_rt.sub_resource_idx = 0;
1845 ret->tid = GetCurrentThreadId();
1847 ret->render_offscreen = wined3d_resource_is_offscreen(&target->resource);
1848 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1849 ret->valid = 1;
1851 ret->glCtx = ctx;
1852 ret->win_handle = swapchain->win_handle;
1853 ret->hdc = hdc;
1854 ret->hdc_is_private = hdc_is_private;
1855 ret->hdc_has_format = TRUE;
1856 ret->pixel_format = pixel_format;
1857 ret->needs_set = 1;
1859 /* Set up the context defaults */
1860 if (!context_set_current(ret))
1862 ERR("Cannot activate context to set up defaults.\n");
1863 device_context_remove(device, ret);
1864 context_release(ret);
1865 if (!wglDeleteContext(ctx))
1866 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1867 goto out;
1870 if (context_debug_output_enabled(gl_info))
1872 GL_EXTCALL(glDebugMessageCallback(wined3d_debug_callback, ret));
1873 if (TRACE_ON(d3d_synchronous))
1874 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
1875 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
1876 if (ERR_ON(d3d))
1878 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR,
1879 GL_DONT_CARE, 0, NULL, GL_TRUE));
1881 if (FIXME_ON(d3d))
1883 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
1884 GL_DONT_CARE, 0, NULL, GL_TRUE));
1885 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
1886 GL_DONT_CARE, 0, NULL, GL_TRUE));
1887 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY,
1888 GL_DONT_CARE, 0, NULL, GL_TRUE));
1890 if (WARN_ON(d3d_perf))
1892 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE,
1893 GL_DONT_CARE, 0, NULL, GL_TRUE));
1897 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
1898 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1900 TRACE("Setting up the screen\n");
1902 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
1904 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1905 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1907 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1908 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1910 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1911 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1913 else
1915 GLuint vao;
1917 GL_EXTCALL(glGenVertexArrays(1, &vao));
1918 GL_EXTCALL(glBindVertexArray(vao));
1919 checkGLcall("creating VAO");
1922 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1923 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1924 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1925 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, 1);");
1927 if (gl_info->supported[ARB_VERTEX_BLEND])
1929 /* Direct3D always uses n-1 weights for n world matrices and uses
1930 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1931 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1932 * enabled as well. */
1933 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1934 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1936 if (gl_info->supported[NV_TEXTURE_SHADER2])
1938 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1939 * the previous texture where to source the offset from is always unit - 1.
1941 for (i = 1; i < gl_info->limits.textures; ++i)
1943 context_active_texture(ret, gl_info, i);
1944 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1945 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + i - 1);
1946 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1949 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1951 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1952 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1953 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1954 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1955 * is ever assigned.
1957 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1958 * program and the dummy program is destroyed when the context is destroyed.
1960 static const char dummy_program[] =
1961 "!!ARBfp1.0\n"
1962 "MOV result.color, fragment.color.primary;\n"
1963 "END\n";
1964 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1965 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1966 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1969 if (gl_info->supported[ARB_POINT_SPRITE])
1971 for (i = 0; i < gl_info->limits.textures; ++i)
1973 context_active_texture(ret, gl_info, i);
1974 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1975 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1979 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1981 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1983 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1985 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1987 if (!(d3d_info->wined3d_creation_flags & WINED3D_NO_PRIMITIVE_RESTART))
1989 if (gl_info->supported[ARB_ES3_COMPATIBILITY])
1991 gl_info->gl_ops.gl.p_glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
1992 checkGLcall("enable GL_PRIMITIVE_RESTART_FIXED_INDEX");
1994 else
1996 FIXME("OpenGL implementation does not support GL_PRIMITIVE_RESTART_FIXED_INDEX.\n");
1999 if (!(d3d_info->wined3d_creation_flags & WINED3D_LEGACY_CUBEMAP_FILTERING)
2000 && gl_info->supported[ARB_SEAMLESS_CUBE_MAP])
2002 gl_info->gl_ops.gl.p_glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
2003 checkGLcall("enable seamless cube map filtering");
2005 if (gl_info->supported[ARB_CLIP_CONTROL])
2006 GL_EXTCALL(glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT));
2007 device->shader_backend->shader_init_context_state(ret);
2008 ret->shader_update_mask = (1u << WINED3D_SHADER_TYPE_PIXEL)
2009 | (1u << WINED3D_SHADER_TYPE_VERTEX)
2010 | (1u << WINED3D_SHADER_TYPE_GEOMETRY)
2011 | (1u << WINED3D_SHADER_TYPE_HULL)
2012 | (1u << WINED3D_SHADER_TYPE_DOMAIN)
2013 | (1u << WINED3D_SHADER_TYPE_COMPUTE);
2015 /* If this happens to be the first context for the device, dummy textures
2016 * are not created yet. In that case, they will be created (and bound) by
2017 * create_dummy_textures right after this context is initialized. */
2018 if (device->dummy_textures.tex_2d)
2019 context_bind_dummy_textures(device, ret);
2021 TRACE("Created context %p.\n", ret);
2023 return ret;
2025 out:
2026 if (hdc) wined3d_release_dc(swapchain->win_handle, hdc);
2027 device->shader_backend->shader_free_context_data(ret);
2028 device->adapter->fragment_pipe->free_context_data(ret);
2029 HeapFree(GetProcessHeap(), 0, ret->texture_type);
2030 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
2031 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
2032 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
2033 HeapFree(GetProcessHeap(), 0, ret->fbo_key);
2034 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
2035 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
2036 HeapFree(GetProcessHeap(), 0, ret);
2037 return NULL;
2040 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
2042 BOOL destroy;
2044 TRACE("Destroying ctx %p\n", context);
2046 /* We delay destroying a context when it is active. The context_release()
2047 * function invokes context_destroy() again while leaving the last level. */
2048 if (context->level)
2050 TRACE("Delaying destruction of context %p.\n", context);
2051 context->destroy_delayed = 1;
2052 /* FIXME: Get rid of a pointer to swapchain from wined3d_context. */
2053 context->swapchain = NULL;
2054 return;
2057 if (context->tid == GetCurrentThreadId() || !context->current)
2059 context_destroy_gl_resources(context);
2060 TlsSetValue(wined3d_context_tls_idx, NULL);
2061 destroy = TRUE;
2063 else
2065 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
2066 in wined3d_adapter may go away in the meantime */
2067 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
2068 *gl_info = *context->gl_info;
2069 context->gl_info = gl_info;
2070 context->destroyed = 1;
2071 destroy = FALSE;
2074 device->shader_backend->shader_free_context_data(context);
2075 device->adapter->fragment_pipe->free_context_data(context);
2076 HeapFree(GetProcessHeap(), 0, context->texture_type);
2077 HeapFree(GetProcessHeap(), 0, context->fbo_key);
2078 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
2079 HeapFree(GetProcessHeap(), 0, context->blit_targets);
2080 device_context_remove(device, context);
2081 if (destroy) HeapFree(GetProcessHeap(), 0, context);
2084 /* Context activation is done by the caller. */
2085 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
2087 const GLdouble projection[] =
2089 2.0 / width, 0.0, 0.0, 0.0,
2090 0.0, 2.0 / height, 0.0, 0.0,
2091 0.0, 0.0, 2.0, 0.0,
2092 -1.0, -1.0, -1.0, 1.0,
2095 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
2096 checkGLcall("glMatrixMode(GL_PROJECTION)");
2097 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
2098 checkGLcall("glLoadMatrixd");
2099 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
2100 checkGLcall("glViewport");
2103 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
2105 const struct wined3d_texture *rt = context->current_rt.texture;
2106 unsigned int level;
2108 if (rt->swapchain && rt->swapchain->front_buffer == rt)
2110 RECT window_size;
2112 GetClientRect(context->win_handle, &window_size);
2113 size->cx = window_size.right - window_size.left;
2114 size->cy = window_size.bottom - window_size.top;
2116 return;
2119 level = context->current_rt.sub_resource_idx % rt->level_count;
2120 size->cx = wined3d_texture_get_level_width(rt, level);
2121 size->cy = wined3d_texture_get_level_height(rt, level);
2124 /*****************************************************************************
2125 * SetupForBlit
2127 * Sets up a context for DirectDraw blitting.
2128 * All texture units are disabled, texture unit 0 is set as current unit
2129 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
2130 * color writing enabled for all channels
2131 * register combiners disabled, shaders disabled
2132 * world matrix is set to identity, texture matrix 0 too
2133 * projection matrix is setup for drawing screen coordinates
2135 * Params:
2136 * This: Device to activate the context for
2137 * context: Context to setup
2139 *****************************************************************************/
2140 /* Context activation is done by the caller. */
2141 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
2143 int i;
2144 const struct wined3d_gl_info *gl_info = context->gl_info;
2145 DWORD sampler;
2146 SIZE rt_size;
2148 TRACE("Setting up context %p for blitting\n", context);
2150 context_get_rt_size(context, &rt_size);
2152 if (context->last_was_blit)
2154 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
2156 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2157 context->blit_w = rt_size.cx;
2158 context->blit_h = rt_size.cy;
2159 /* No need to dirtify here, the states are still dirtified because
2160 * they weren't applied since the last SetupForBlit() call. */
2162 TRACE("Context is already set up for blitting, nothing to do\n");
2163 return;
2165 context->last_was_blit = TRUE;
2167 /* Disable all textures. The caller can then bind a texture it wants to blit
2168 * from
2170 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
2171 * function texture unit. No need to care for higher samplers
2173 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
2175 sampler = context->rev_tex_unit_map[i];
2176 context_active_texture(context, gl_info, i);
2178 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2180 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2181 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2183 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2184 checkGLcall("glDisable GL_TEXTURE_3D");
2185 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2187 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2188 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2190 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2191 checkGLcall("glDisable GL_TEXTURE_2D");
2193 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2194 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
2196 if (sampler != WINED3D_UNMAPPED_STAGE)
2198 if (sampler < MAX_TEXTURES)
2199 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2200 context_invalidate_state(context, STATE_SAMPLER(sampler));
2203 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
2204 GL_EXTCALL(glBindSampler(0, 0));
2205 context_active_texture(context, gl_info, 0);
2207 sampler = context->rev_tex_unit_map[0];
2209 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2211 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2212 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2214 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2215 checkGLcall("glDisable GL_TEXTURE_3D");
2216 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2218 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2219 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2221 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2222 checkGLcall("glDisable GL_TEXTURE_2D");
2224 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2226 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
2227 checkGLcall("glMatrixMode(GL_TEXTURE)");
2228 gl_info->gl_ops.gl.p_glLoadIdentity();
2229 checkGLcall("glLoadIdentity()");
2231 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2233 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
2234 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
2235 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
2238 if (sampler != WINED3D_UNMAPPED_STAGE)
2240 if (sampler < MAX_TEXTURES)
2242 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
2243 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2245 context_invalidate_state(context, STATE_SAMPLER(sampler));
2248 /* Other misc states */
2249 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2250 checkGLcall("glDisable(GL_ALPHA_TEST)");
2251 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2252 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2253 checkGLcall("glDisable GL_LIGHTING");
2254 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2255 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2256 checkGLcall("glDisable GL_DEPTH_TEST");
2257 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2258 glDisableWINE(GL_FOG);
2259 checkGLcall("glDisable GL_FOG");
2260 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
2261 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2262 checkGLcall("glDisable GL_BLEND");
2263 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2264 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2265 checkGLcall("glDisable GL_CULL_FACE");
2266 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2267 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2268 checkGLcall("glDisable GL_STENCIL_TEST");
2269 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2270 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2271 checkGLcall("glDisable GL_SCISSOR_TEST");
2272 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2273 if (gl_info->supported[ARB_POINT_SPRITE])
2275 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2276 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2277 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2279 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2280 checkGLcall("glColorMask");
2281 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2282 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2283 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2284 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2285 if (gl_info->supported[EXT_SECONDARY_COLOR])
2287 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2288 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2289 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2292 /* Setup transforms */
2293 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2294 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2295 gl_info->gl_ops.gl.p_glLoadIdentity();
2296 checkGLcall("glLoadIdentity()");
2297 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2299 context->last_was_rhw = TRUE;
2300 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2302 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2303 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2304 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2305 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2306 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2307 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2308 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2310 /* FIXME: Make draw_textured_quad() able to work with a upper left origin. */
2311 if (gl_info->supported[ARB_CLIP_CONTROL])
2312 GL_EXTCALL(glClipControl(GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE));
2314 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2316 /* Disable shaders */
2317 device->shader_backend->shader_disable(device->shader_priv, context);
2319 context->blit_w = rt_size.cx;
2320 context->blit_h = rt_size.cy;
2321 context_invalidate_state(context, STATE_VIEWPORT);
2322 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2325 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2327 return rt_mask & (1u << 31);
2330 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2332 return rt_mask & ~(1u << 31);
2335 /* Context activation is done by the caller. */
2336 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2338 const struct wined3d_gl_info *gl_info = context->gl_info;
2340 if (!rt_mask)
2342 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2343 checkGLcall("glDrawBuffer()");
2345 else if (is_rt_mask_onscreen(rt_mask))
2347 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2348 checkGLcall("glDrawBuffer()");
2350 else
2352 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2354 unsigned int i = 0;
2356 while (rt_mask)
2358 if (rt_mask & 1)
2359 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2360 else
2361 context->draw_buffers[i] = GL_NONE;
2363 rt_mask >>= 1;
2364 ++i;
2367 if (gl_info->supported[ARB_DRAW_BUFFERS])
2369 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2370 checkGLcall("glDrawBuffers()");
2372 else
2374 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2375 checkGLcall("glDrawBuffer()");
2378 else
2380 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2385 /* Context activation is done by the caller. */
2386 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2388 const struct wined3d_gl_info *gl_info = context->gl_info;
2389 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2390 DWORD new_mask = context_generate_rt_mask(buffer);
2392 if (new_mask == *current_mask)
2393 return;
2395 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2396 checkGLcall("glDrawBuffer()");
2398 *current_mask = new_mask;
2401 /* Context activation is done by the caller. */
2402 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2404 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2405 checkGLcall("glActiveTexture");
2406 context->active_texture = unit;
2409 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2411 const struct wined3d_gl_info *gl_info = context->gl_info;
2412 DWORD unit = context->active_texture;
2413 DWORD old_texture_type = context->texture_type[unit];
2415 if (name)
2417 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2418 checkGLcall("glBindTexture");
2420 else
2422 target = GL_NONE;
2425 if (old_texture_type != target)
2427 const struct wined3d_device *device = context->device;
2429 switch (old_texture_type)
2431 case GL_NONE:
2432 /* nothing to do */
2433 break;
2434 case GL_TEXTURE_2D:
2435 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_textures.tex_2d);
2436 checkGLcall("glBindTexture");
2437 break;
2438 case GL_TEXTURE_2D_ARRAY:
2439 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, device->dummy_textures.tex_2d_array);
2440 checkGLcall("glBindTexture");
2441 break;
2442 case GL_TEXTURE_RECTANGLE_ARB:
2443 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_textures.tex_rect);
2444 checkGLcall("glBindTexture");
2445 break;
2446 case GL_TEXTURE_CUBE_MAP:
2447 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_textures.tex_cube);
2448 checkGLcall("glBindTexture");
2449 break;
2450 case GL_TEXTURE_CUBE_MAP_ARRAY:
2451 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, device->dummy_textures.tex_cube_array);
2452 checkGLcall("glBindTexture");
2453 break;
2454 case GL_TEXTURE_3D:
2455 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_textures.tex_3d);
2456 checkGLcall("glBindTexture");
2457 break;
2458 case GL_TEXTURE_BUFFER:
2459 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_BUFFER, device->dummy_textures.tex_buffer);
2460 checkGLcall("glBindTexture");
2461 break;
2462 default:
2463 ERR("Unexpected texture target %#x.\n", old_texture_type);
2466 context->texture_type[unit] = target;
2470 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2472 if (context->render_offscreen == offscreen) return;
2474 context_invalidate_state(context, STATE_VIEWPORT);
2475 context_invalidate_state(context, STATE_SCISSORRECT);
2476 if (!context->gl_info->supported[ARB_CLIP_CONTROL])
2478 context_invalidate_state(context, STATE_FRONTFACE);
2479 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2480 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2482 if (context->gl_info->supported[ARB_FRAGMENT_COORD_CONVENTIONS])
2483 context_invalidate_state(context, STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL));
2484 context->render_offscreen = offscreen;
2487 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2488 const struct wined3d_format *required)
2490 if (existing == required)
2491 return TRUE;
2492 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2493 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2494 return FALSE;
2495 if (existing->depth_size < required->depth_size)
2496 return FALSE;
2497 /* If stencil bits are used the exact amount is required - otherwise
2498 * wrapping won't work correctly. */
2499 if (required->stencil_size && required->stencil_size != existing->stencil_size)
2500 return FALSE;
2501 return TRUE;
2504 /* Context activation is done by the caller. */
2505 static void context_validate_onscreen_formats(struct wined3d_context *context,
2506 const struct wined3d_rendertarget_view *depth_stencil)
2508 /* Onscreen surfaces are always in a swapchain */
2509 struct wined3d_swapchain *swapchain = context->current_rt.texture->swapchain;
2511 if (context->render_offscreen || !depth_stencil) return;
2512 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2514 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2515 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2516 * format. */
2517 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2519 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2520 if (!(wined3d_texture_load_location(context->current_rt.texture, context->current_rt.sub_resource_idx,
2521 context, WINED3D_LOCATION_TEXTURE_RGB)))
2522 ERR("Failed to load location.\n");
2523 swapchain->render_to_fbo = TRUE;
2524 swapchain_update_draw_bindings(swapchain);
2525 context_set_render_offscreen(context, TRUE);
2528 GLenum context_get_offscreen_gl_buffer(const struct wined3d_context *context)
2530 switch (wined3d_settings.offscreen_rendering_mode)
2532 case ORM_FBO:
2533 return GL_COLOR_ATTACHMENT0;
2535 case ORM_BACKBUFFER:
2536 return context->aux_buffers > 0 ? GL_AUX0 : GL_BACK;
2538 default:
2539 FIXME("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
2540 return GL_BACK;
2544 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_context *context, struct wined3d_texture *rt)
2546 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2547 return 0;
2548 else if (rt->swapchain)
2549 return context_generate_rt_mask_from_resource(&rt->resource);
2550 else
2551 return context_generate_rt_mask(context_get_offscreen_gl_buffer(context));
2554 /* Context activation is done by the caller. */
2555 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2557 struct wined3d_texture *rt = context->current_rt.texture;
2558 struct wined3d_surface *surface;
2559 DWORD rt_mask, *cur_mask;
2561 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2563 context_validate_onscreen_formats(context, NULL);
2565 if (context->render_offscreen)
2567 wined3d_texture_load(rt, context, FALSE);
2569 surface = rt->sub_resources[context->current_rt.sub_resource_idx].u.surface;
2570 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, surface, NULL, rt->resource.draw_binding);
2571 if (rt->resource.format->id != WINED3DFMT_NULL)
2572 rt_mask = 1;
2573 else
2574 rt_mask = 0;
2576 else
2578 context->current_fbo = NULL;
2579 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2580 rt_mask = context_generate_rt_mask_from_resource(&rt->resource);
2583 else
2585 rt_mask = context_generate_rt_mask_no_fbo(context, rt);
2588 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2590 if (rt_mask != *cur_mask)
2592 context_apply_draw_buffers(context, rt_mask);
2593 *cur_mask = rt_mask;
2596 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2598 context_check_fbo_status(context, GL_FRAMEBUFFER);
2601 SetupForBlit(device, context);
2602 context_invalidate_state(context, STATE_FRAMEBUFFER);
2605 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2606 const struct wined3d_rendertarget_view *ds)
2608 unsigned int i;
2610 if (ds) return TRUE;
2612 for (i = 0; i < rt_count; ++i)
2614 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2615 return TRUE;
2618 WARN("Invalid render target config, need at least one attachment.\n");
2619 return FALSE;
2622 /* Context activation is done by the caller. */
2623 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_state *state,
2624 UINT rt_count, const struct wined3d_fb_state *fb)
2626 struct wined3d_rendertarget_view **rts = fb->render_targets;
2627 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2628 const struct wined3d_gl_info *gl_info = context->gl_info;
2629 DWORD rt_mask = 0, *cur_mask;
2630 UINT i;
2632 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != state->fb
2633 || rt_count != gl_info->limits.buffers)
2635 if (!context_validate_rt_config(rt_count, rts, dsv))
2636 return FALSE;
2638 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2640 context_validate_onscreen_formats(context, dsv);
2642 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2644 for (i = 0; i < rt_count; ++i)
2646 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(rts[i]);
2647 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2648 rt_mask |= (1u << i);
2650 while (i < gl_info->limits.buffers)
2652 context->blit_targets[i] = NULL;
2653 ++i;
2655 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2656 wined3d_rendertarget_view_get_surface(dsv),
2657 rt_count ? rts[0]->resource->draw_binding : 0,
2658 dsv ? dsv->resource->draw_binding : 0);
2660 else
2662 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2663 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2664 rt_mask = context_generate_rt_mask_from_resource(rts[0]->resource);
2667 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2668 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2669 * state management allows this */
2670 context_invalidate_state(context, STATE_FRAMEBUFFER);
2672 else
2674 rt_mask = context_generate_rt_mask_no_fbo(context,
2675 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
2678 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2679 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
2681 for (i = 0; i < rt_count; ++i)
2683 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2684 rt_mask |= (1u << i);
2687 else
2689 rt_mask = context_generate_rt_mask_no_fbo(context,
2690 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
2693 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2695 if (rt_mask != *cur_mask)
2697 context_apply_draw_buffers(context, rt_mask);
2698 *cur_mask = rt_mask;
2699 context_invalidate_state(context, STATE_FRAMEBUFFER);
2702 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2704 context_check_fbo_status(context, GL_FRAMEBUFFER);
2707 context->last_was_blit = FALSE;
2709 /* Blending and clearing should be orthogonal, but tests on the nvidia
2710 * driver show that disabling blending when clearing improves the clearing
2711 * performance incredibly. */
2712 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2713 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2714 if (rt_count && gl_info->supported[ARB_FRAMEBUFFER_SRGB])
2716 if (needs_srgb_write(context, state, fb))
2717 gl_info->gl_ops.gl.p_glEnable(GL_FRAMEBUFFER_SRGB);
2718 else
2719 gl_info->gl_ops.gl.p_glDisable(GL_FRAMEBUFFER_SRGB);
2720 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2722 checkGLcall("setting up state for clear");
2724 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2725 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2726 context_invalidate_state(context, STATE_SCISSORRECT);
2728 return TRUE;
2731 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_state *state)
2733 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
2734 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2735 DWORD rt_mask, rt_mask_bits;
2736 unsigned int i;
2738 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2739 return context_generate_rt_mask_no_fbo(context, wined3d_rendertarget_view_get_surface(rts[0])->container);
2740 else if (!context->render_offscreen)
2741 return context_generate_rt_mask_from_resource(rts[0]->resource);
2743 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2744 rt_mask &= context->d3d_info->valid_rt_mask;
2745 rt_mask_bits = rt_mask;
2746 i = 0;
2747 while (rt_mask_bits)
2749 rt_mask_bits &= ~(1u << i);
2750 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
2751 rt_mask &= ~(1u << i);
2753 i++;
2756 return rt_mask;
2759 /* Context activation is done by the caller. */
2760 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2762 DWORD rt_mask = find_draw_buffers_mask(context, state);
2763 const struct wined3d_fb_state *fb = state->fb;
2764 DWORD *cur_mask;
2766 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2768 if (!context->render_offscreen)
2770 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2771 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2773 else
2775 unsigned int i;
2777 for (i = 0; i < context->gl_info->limits.buffers; ++i)
2779 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(fb->render_targets[i]);
2781 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2782 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
2783 fb->render_targets[0] ? fb->render_targets[0]->resource->draw_binding : 0,
2784 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
2788 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2789 if (rt_mask != *cur_mask)
2791 context_apply_draw_buffers(context, rt_mask);
2792 *cur_mask = rt_mask;
2794 context->constant_update_mask |= WINED3D_SHADER_CONST_PS_Y_CORR;
2797 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
2799 DWORD i = context->rev_tex_unit_map[unit];
2800 DWORD j = context->tex_unit_map[stage];
2802 TRACE("Mapping stage %u to unit %u.\n", stage, unit);
2803 context->tex_unit_map[stage] = unit;
2804 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2805 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2807 context->rev_tex_unit_map[unit] = stage;
2808 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2809 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2812 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
2814 DWORD i;
2816 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2817 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
2820 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
2821 const struct wined3d_state *state)
2823 UINT i, start, end;
2825 context->fixed_function_usage_map = 0;
2826 for (i = 0; i < MAX_TEXTURES; ++i)
2828 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2829 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2830 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2831 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2832 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2833 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2834 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2835 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2837 /* Not used, and disable higher stages. */
2838 if (color_op == WINED3D_TOP_DISABLE)
2839 break;
2841 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2842 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2843 || ((color_arg3 == WINED3DTA_TEXTURE)
2844 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2845 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2846 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2847 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2848 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2849 context->fixed_function_usage_map |= (1u << i);
2851 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2852 && i < MAX_TEXTURES - 1)
2853 context->fixed_function_usage_map |= (1u << (i + 1));
2856 if (i < context->lowest_disabled_stage)
2858 start = i;
2859 end = context->lowest_disabled_stage;
2861 else
2863 start = context->lowest_disabled_stage;
2864 end = i;
2867 context->lowest_disabled_stage = i;
2868 for (i = start + 1; i < end; ++i)
2870 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
2874 static void context_map_fixed_function_samplers(struct wined3d_context *context,
2875 const struct wined3d_state *state)
2877 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2878 unsigned int i, tex;
2879 WORD ffu_map;
2881 ffu_map = context->fixed_function_usage_map;
2883 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
2884 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
2886 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2888 if (!(ffu_map & 1))
2889 continue;
2891 if (context->tex_unit_map[i] != i)
2893 context_map_stage(context, i, i);
2894 context_invalidate_state(context, STATE_SAMPLER(i));
2895 context_invalidate_texture_stage(context, i);
2898 return;
2901 /* Now work out the mapping */
2902 tex = 0;
2903 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2905 if (!(ffu_map & 1))
2906 continue;
2908 if (context->tex_unit_map[i] != tex)
2910 context_map_stage(context, i, tex);
2911 context_invalidate_state(context, STATE_SAMPLER(i));
2912 context_invalidate_texture_stage(context, i);
2915 ++tex;
2919 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
2921 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2922 const struct wined3d_shader_resource_info *resource_info =
2923 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2924 unsigned int i;
2926 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2928 if (resource_info[i].type && context->tex_unit_map[i] != i)
2930 context_map_stage(context, i, i);
2931 context_invalidate_state(context, STATE_SAMPLER(i));
2932 if (i < d3d_info->limits.ffp_blend_stages)
2933 context_invalidate_texture_stage(context, i);
2938 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
2939 const struct wined3d_shader_resource_info *ps_resource_info, DWORD unit)
2941 DWORD current_mapping = context->rev_tex_unit_map[unit];
2943 /* Not currently used */
2944 if (current_mapping == WINED3D_UNMAPPED_STAGE)
2945 return TRUE;
2947 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
2949 /* Used by a fragment sampler */
2951 if (!ps_resource_info)
2953 /* No pixel shader, check fixed function */
2954 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1u << current_mapping));
2957 /* Pixel shader, check the shader's sampler map */
2958 return !ps_resource_info[current_mapping].type;
2961 return TRUE;
2964 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
2966 const struct wined3d_shader_resource_info *vs_resource_info =
2967 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
2968 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
2969 const struct wined3d_gl_info *gl_info = context->gl_info;
2970 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.graphics_samplers) - 1;
2971 int i;
2973 /* Note that we only care if a resource is used or not, not the
2974 * resource's specific type. Otherwise we'd need to call
2975 * shader_update_samplers() here for 1.x pixelshaders. */
2976 if (ps)
2977 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2979 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2981 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2982 if (vs_resource_info[i].type)
2984 while (start >= 0)
2986 if (context_unit_free_for_vs(context, ps_resource_info, start))
2988 if (context->tex_unit_map[vsampler_idx] != start)
2990 context_map_stage(context, vsampler_idx, start);
2991 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
2994 --start;
2995 break;
2998 --start;
3000 if (context->tex_unit_map[vsampler_idx] == WINED3D_UNMAPPED_STAGE)
3001 WARN("Couldn't find a free texture unit for vertex sampler %u.\n", i);
3006 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
3008 const struct wined3d_gl_info *gl_info = context->gl_info;
3009 BOOL vs = use_vs(state);
3010 BOOL ps = use_ps(state);
3012 if (!ps)
3013 context_update_fixed_function_usage_map(context, state);
3015 /* Try to go for a 1:1 mapping of the samplers when possible. Pixel shaders
3016 * need a 1:1 map at the moment.
3017 * When the mapping of a stage is changed, sampler and ALL texture stage
3018 * states have to be reset. */
3020 if (gl_info->limits.graphics_samplers >= MAX_COMBINED_SAMPLERS)
3021 return;
3023 if (ps)
3024 context_map_psamplers(context, state);
3025 else
3026 context_map_fixed_function_samplers(context, state);
3028 if (vs)
3029 context_map_vsamplers(context, ps, state);
3032 /* Context activation is done by the caller. */
3033 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
3035 DWORD rt_mask, *cur_mask;
3037 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
3039 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3040 rt_mask = find_draw_buffers_mask(context, state);
3041 if (rt_mask != *cur_mask)
3043 context_apply_draw_buffers(context, rt_mask);
3044 *cur_mask = rt_mask;
3048 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
3050 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
3051 *regnum = WINED3D_FFP_POSITION;
3052 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
3053 *regnum = WINED3D_FFP_BLENDWEIGHT;
3054 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
3055 *regnum = WINED3D_FFP_BLENDINDICES;
3056 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
3057 *regnum = WINED3D_FFP_NORMAL;
3058 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
3059 *regnum = WINED3D_FFP_PSIZE;
3060 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
3061 *regnum = WINED3D_FFP_DIFFUSE;
3062 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
3063 *regnum = WINED3D_FFP_SPECULAR;
3064 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
3065 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
3066 else
3068 FIXME("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
3069 *regnum = ~0U;
3070 return FALSE;
3073 return TRUE;
3076 /* Context activation is done by the caller. */
3077 void wined3d_stream_info_from_declaration(struct wined3d_stream_info *stream_info,
3078 const struct wined3d_state *state, const struct wined3d_gl_info *gl_info,
3079 const struct wined3d_d3d_info *d3d_info)
3081 /* We need to deal with frequency data! */
3082 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
3083 BOOL generic_attributes = d3d_info->ffp_generic_attributes;
3084 BOOL use_vshader = use_vs(state);
3085 unsigned int i;
3087 stream_info->use_map = 0;
3088 stream_info->swizzle_map = 0;
3089 stream_info->position_transformed = 0;
3091 if (!declaration)
3092 return;
3094 stream_info->position_transformed = declaration->position_transformed;
3096 /* Translate the declaration into strided data. */
3097 for (i = 0; i < declaration->element_count; ++i)
3099 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
3100 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
3101 BOOL stride_used;
3102 unsigned int idx;
3104 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
3105 element, i + 1, declaration->element_count);
3107 if (!stream->buffer)
3108 continue;
3110 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
3112 if (use_vshader)
3114 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
3116 stride_used = FALSE;
3118 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
3120 /* TODO: Assuming vertexdeclarations are usually used with the
3121 * same or a similar shader, it might be worth it to store the
3122 * last used output slot and try that one first. */
3123 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
3124 element->usage, element->usage_idx, &idx);
3126 else
3128 idx = element->output_slot;
3129 stride_used = TRUE;
3132 else
3134 if (!generic_attributes && !element->ffp_valid)
3136 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
3137 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
3138 stride_used = FALSE;
3140 else
3142 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
3146 if (stride_used)
3148 TRACE("Load %s array %u [usage %s, usage_idx %u, "
3149 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
3150 use_vshader ? "shader": "fixed function", idx,
3151 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
3152 element->offset, stream->stride, debug_d3dformat(element->format->id),
3153 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
3155 stream_info->elements[idx].format = element->format;
3156 stream_info->elements[idx].data.buffer_object = 0;
3157 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
3158 stream_info->elements[idx].stride = stream->stride;
3159 stream_info->elements[idx].stream_idx = element->input_slot;
3160 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
3162 stream_info->elements[idx].divisor = 1;
3164 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
3166 stream_info->elements[idx].divisor = element->instance_data_step_rate;
3167 if (!element->instance_data_step_rate)
3168 FIXME("Instance step rate 0 not implemented.\n");
3170 else
3172 stream_info->elements[idx].divisor = 0;
3175 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3176 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
3178 stream_info->swizzle_map |= 1u << idx;
3180 stream_info->use_map |= 1u << idx;
3185 /* Context activation is done by the caller. */
3186 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
3188 struct wined3d_stream_info *stream_info = &context->stream_info;
3189 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3190 const struct wined3d_gl_info *gl_info = context->gl_info;
3191 DWORD prev_all_vbo = stream_info->all_vbo;
3192 unsigned int i;
3193 WORD map;
3195 wined3d_stream_info_from_declaration(stream_info, state, gl_info, d3d_info);
3197 stream_info->all_vbo = 1;
3198 context->num_buffer_queries = 0;
3199 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
3201 struct wined3d_stream_info_element *element;
3202 struct wined3d_bo_address data;
3203 struct wined3d_buffer *buffer;
3205 if (!(map & 1))
3206 continue;
3208 element = &stream_info->elements[i];
3209 buffer = state->streams[element->stream_idx].buffer;
3211 /* We can't use VBOs if the base vertex index is negative. OpenGL
3212 * doesn't accept negative offsets (or rather offsets bigger than the
3213 * VBO, because the pointer is unsigned), so use system memory
3214 * sources. In most sane cases the pointer - offset will still be > 0,
3215 * otherwise it will wrap around to some big value. Hope that with the
3216 * indices the driver wraps it back internally. If not,
3217 * draw_primitive_immediate_mode() is needed, including a vertex buffer
3218 * path. */
3219 if (state->load_base_vertex_index < 0)
3221 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
3222 state->load_base_vertex_index);
3223 element->data.buffer_object = 0;
3224 element->data.addr += (ULONG_PTR)wined3d_buffer_load_sysmem(buffer, context);
3225 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
3226 FIXME("System memory vertex data load offset is negative!\n");
3228 else
3230 wined3d_buffer_load(buffer, context, state);
3231 wined3d_buffer_get_memory(buffer, &data, buffer->locations);
3232 element->data.buffer_object = data.buffer_object;
3233 element->data.addr += (ULONG_PTR)data.addr;
3236 if (!element->data.buffer_object)
3237 stream_info->all_vbo = 0;
3239 if (buffer->query)
3240 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
3242 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
3245 if (prev_all_vbo != stream_info->all_vbo)
3246 context_invalidate_state(context, STATE_INDEXBUFFER);
3248 context->use_immediate_mode_draw = FALSE;
3250 if (stream_info->all_vbo)
3251 return;
3253 if (use_vs(state))
3255 if (state->vertex_declaration->half_float_conv_needed)
3257 TRACE("Using immediate mode draw with vertex shaders for FLOAT16 conversion.\n");
3258 context->use_immediate_mode_draw = TRUE;
3261 else
3263 WORD slow_mask = -!d3d_info->ffp_generic_attributes & (1u << WINED3D_FFP_PSIZE);
3264 slow_mask |= -(!gl_info->supported[ARB_VERTEX_ARRAY_BGRA] && !d3d_info->ffp_generic_attributes)
3265 & ((1u << WINED3D_FFP_DIFFUSE) | (1u << WINED3D_FFP_SPECULAR) | (1u << WINED3D_FFP_BLENDWEIGHT));
3267 if ((stream_info->position_transformed && !d3d_info->xyzrhw)
3268 || (stream_info->use_map & slow_mask))
3269 context->use_immediate_mode_draw = TRUE;
3273 /* Context activation is done by the caller. */
3274 static void context_preload_texture(struct wined3d_context *context,
3275 const struct wined3d_state *state, unsigned int idx)
3277 struct wined3d_texture *texture;
3279 if (!(texture = state->textures[idx]))
3280 return;
3282 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3285 /* Context activation is done by the caller. */
3286 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3288 unsigned int i;
3290 if (use_vs(state))
3292 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3294 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3295 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3299 if (use_ps(state))
3301 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3303 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3304 context_preload_texture(context, state, i);
3307 else
3309 WORD ffu_map = context->fixed_function_usage_map;
3311 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3313 if (ffu_map & 1)
3314 context_preload_texture(context, state, i);
3319 static void context_load_shader_resources(struct wined3d_context *context, const struct wined3d_state *state,
3320 unsigned int shader_mask)
3322 struct wined3d_shader_sampler_map_entry *entry;
3323 struct wined3d_shader_resource_view *view;
3324 struct wined3d_shader *shader;
3325 unsigned int i, j;
3327 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3329 if (!(shader_mask & (1u << i)))
3330 continue;
3332 if (!(shader = state->shader[i]))
3333 continue;
3335 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3337 if (state->cb[i][j])
3338 wined3d_buffer_load(state->cb[i][j], context, state);
3341 for (j = 0; j < shader->reg_maps.sampler_map.count; ++j)
3343 entry = &shader->reg_maps.sampler_map.entries[j];
3345 if (!(view = state->shader_resource_view[i][entry->resource_idx]))
3347 WARN("No resource view bound at index %u, %u.\n", i, entry->resource_idx);
3348 continue;
3351 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3352 wined3d_buffer_load(buffer_from_resource(view->resource), context, state);
3353 else
3354 wined3d_texture_load(texture_from_resource(view->resource), context, FALSE);
3359 static void context_bind_shader_resources(struct wined3d_context *context,
3360 const struct wined3d_state *state, enum wined3d_shader_type shader_type,
3361 unsigned int base_idx, unsigned int count)
3363 const struct wined3d_gl_info *gl_info = context->gl_info;
3364 const struct wined3d_device *device = context->device;
3365 struct wined3d_shader_sampler_map_entry *entry;
3366 struct wined3d_shader_resource_view *view;
3367 unsigned int shader_sampler_count, i;
3368 const struct wined3d_shader *shader;
3369 struct wined3d_sampler *sampler;
3370 GLuint sampler_name;
3372 if (!(shader = state->shader[shader_type]))
3373 return;
3375 shader_sampler_count = shader->reg_maps.sampler_map.count;
3376 if (shader_sampler_count > count)
3377 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3378 shader, shader_sampler_count, count);
3379 count = min(shader_sampler_count, count);
3381 for (i = 0; i < count; ++i)
3383 entry = &shader->reg_maps.sampler_map.entries[i];
3385 if (!(view = state->shader_resource_view[shader_type][entry->resource_idx]))
3387 WARN("No resource view bound at index %u, %u.\n", shader_type, entry->resource_idx);
3388 continue;
3391 if (entry->sampler_idx == WINED3D_SAMPLER_DEFAULT)
3392 sampler_name = device->default_sampler;
3393 else if ((sampler = state->sampler[shader_type][entry->sampler_idx]))
3394 sampler_name = sampler->name;
3395 else
3396 sampler_name = device->null_sampler;
3398 context_active_texture(context, gl_info, base_idx + entry->bind_idx);
3399 GL_EXTCALL(glBindSampler(base_idx + entry->bind_idx, sampler_name));
3400 checkGLcall("glBindSampler");
3401 wined3d_shader_resource_view_bind(view, context);
3405 static void context_bind_graphics_shader_resources(struct wined3d_context *context,
3406 const struct wined3d_state *state)
3408 unsigned int i, base_idx, count;
3410 for (i = 0; i < WINED3D_SHADER_TYPE_GRAPHICS_COUNT; ++i)
3412 wined3d_gl_limits_get_texture_unit_range(&context->gl_info->limits, i, &base_idx, &count);
3413 context_bind_shader_resources(context, state, i, base_idx, count);
3417 static void context_load_unordered_access_resources(struct wined3d_context *context,
3418 const struct wined3d_shader *shader, struct wined3d_unordered_access_view * const *views)
3420 struct wined3d_unordered_access_view *view;
3421 struct wined3d_texture *texture;
3422 struct wined3d_buffer *buffer;
3423 unsigned int i;
3425 context->uses_uavs = 0;
3427 if (!shader)
3428 return;
3430 for (i = 0; i < MAX_UNORDERED_ACCESS_VIEWS; ++i)
3432 if (!(view = views[i]))
3433 continue;
3435 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3437 buffer = buffer_from_resource(view->resource);
3438 wined3d_buffer_load_location(buffer, context, WINED3D_LOCATION_BUFFER);
3439 wined3d_unordered_access_view_invalidate_location(view, ~WINED3D_LOCATION_BUFFER);
3441 else
3443 texture = texture_from_resource(view->resource);
3444 wined3d_texture_load(texture, context, FALSE);
3445 wined3d_unordered_access_view_invalidate_location(view, ~WINED3D_LOCATION_TEXTURE_RGB);
3448 context->uses_uavs = 1;
3452 static void context_bind_unordered_access_views(struct wined3d_context *context,
3453 const struct wined3d_shader *shader, struct wined3d_unordered_access_view * const *views)
3455 const struct wined3d_gl_info *gl_info = context->gl_info;
3456 struct wined3d_unordered_access_view *view;
3457 GLuint texture_name;
3458 unsigned int i;
3459 GLint level;
3461 if (!shader)
3462 return;
3464 for (i = 0; i < MAX_UNORDERED_ACCESS_VIEWS; ++i)
3466 if (!(view = views[i]))
3468 if (shader->reg_maps.uav_resource_info[i].type)
3469 WARN("No unordered access view bound at index %u.\n", i);
3470 GL_EXTCALL(glBindImageTexture(i, 0, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8));
3471 continue;
3474 if (view->gl_view.name)
3476 texture_name = view->gl_view.name;
3477 level = 0;
3479 else if (view->resource->type != WINED3D_RTYPE_BUFFER)
3481 struct wined3d_texture *texture = texture_from_resource(view->resource);
3482 texture_name = wined3d_texture_get_gl_texture(texture, FALSE)->name;
3483 level = view->desc.u.texture.level_idx;
3485 else
3487 FIXME("Unsupported buffer unordered access view.\n");
3488 GL_EXTCALL(glBindImageTexture(i, 0, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8));
3489 continue;
3492 GL_EXTCALL(glBindImageTexture(i, texture_name, level, GL_TRUE, 0, GL_READ_WRITE,
3493 view->format->glInternal));
3495 if (view->counter_bo)
3496 GL_EXTCALL(glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, i, view->counter_bo));
3498 checkGLcall("Bind unordered access views");
3501 /* Context activation is done by the caller. */
3502 BOOL context_apply_draw_state(struct wined3d_context *context,
3503 const struct wined3d_device *device, const struct wined3d_state *state)
3505 const struct StateEntry *state_table = context->state_table;
3506 const struct wined3d_gl_info *gl_info = context->gl_info;
3507 const struct wined3d_fb_state *fb = state->fb;
3508 unsigned int i;
3509 WORD map;
3511 if (!context_validate_rt_config(gl_info->limits.buffers, fb->render_targets, fb->depth_stencil))
3512 return FALSE;
3514 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3516 context_validate_onscreen_formats(context, fb->depth_stencil);
3519 /* Preload resources before FBO setup. Texture preload in particular may
3520 * result in changes to the current FBO, due to using e.g. FBO blits for
3521 * updating a resource location. */
3522 context_update_tex_unit_map(context, state);
3523 context_preload_textures(context, state);
3524 context_load_shader_resources(context, state, ~(1u << WINED3D_SHADER_TYPE_COMPUTE));
3525 context_load_unordered_access_resources(context, state->shader[WINED3D_SHADER_TYPE_PIXEL],
3526 state->unordered_access_view[WINED3D_PIPELINE_GRAPHICS]);
3527 /* TODO: Right now the dependency on the vertex shader is necessary
3528 * since wined3d_stream_info_from_declaration() depends on the reg_maps of
3529 * the current VS but maybe it's possible to relax the coupling in some
3530 * situations at least. */
3531 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3532 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3534 context_update_stream_info(context, state);
3536 else
3538 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3540 if (map & 1)
3541 wined3d_buffer_load(state->streams[context->stream_info.elements[i].stream_idx].buffer,
3542 context, state);
3544 /* Loading the buffers above may have invalidated the stream info. */
3545 if (isStateDirty(context, STATE_STREAMSRC))
3546 context_update_stream_info(context, state);
3548 if (state->index_buffer)
3550 if (context->stream_info.all_vbo)
3551 wined3d_buffer_load(state->index_buffer, context, state);
3552 else
3553 wined3d_buffer_load_sysmem(state->index_buffer, context);
3556 for (i = 0; i < context->numDirtyEntries; ++i)
3558 DWORD rep = context->dirtyArray[i];
3559 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3560 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3561 context->isStateDirty[idx] &= ~(1u << shift);
3562 state_table[rep].apply(context, state, rep);
3565 if (context->shader_update_mask & ~(1u << WINED3D_SHADER_TYPE_COMPUTE))
3567 device->shader_backend->shader_select(device->shader_priv, context, state);
3568 context->shader_update_mask &= 1u << WINED3D_SHADER_TYPE_COMPUTE;
3571 if (context->constant_update_mask)
3573 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3574 context->constant_update_mask = 0;
3577 if (context->update_shader_resource_bindings)
3579 context_bind_graphics_shader_resources(context, state);
3580 context->update_shader_resource_bindings = 0;
3581 if (gl_info->limits.combined_samplers == gl_info->limits.graphics_samplers)
3582 context->update_compute_shader_resource_bindings = 1;
3585 if (context->update_unordered_access_view_bindings)
3587 context_bind_unordered_access_views(context,
3588 state->shader[WINED3D_SHADER_TYPE_PIXEL],
3589 state->unordered_access_view[WINED3D_PIPELINE_GRAPHICS]);
3590 context->update_unordered_access_view_bindings = 0;
3591 context->update_compute_unordered_access_view_bindings = 1;
3594 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3596 context_check_fbo_status(context, GL_FRAMEBUFFER);
3599 context->numDirtyEntries = 0; /* This makes the whole list clean */
3600 context->last_was_blit = FALSE;
3602 return TRUE;
3605 void context_apply_compute_state(struct wined3d_context *context,
3606 const struct wined3d_device *device, const struct wined3d_state *state)
3608 const struct StateEntry *state_table = context->state_table;
3609 const struct wined3d_gl_info *gl_info = context->gl_info;
3610 unsigned int state_id, i, j;
3612 context_load_shader_resources(context, state, 1u << WINED3D_SHADER_TYPE_COMPUTE);
3613 context_load_unordered_access_resources(context, state->shader[WINED3D_SHADER_TYPE_COMPUTE],
3614 state->unordered_access_view[WINED3D_PIPELINE_COMPUTE]);
3616 for (i = 0, state_id = STATE_COMPUTE_OFFSET; i < ARRAY_SIZE(context->dirty_compute_states); ++i)
3618 for (j = 0; j < sizeof(*context->dirty_compute_states) * CHAR_BIT; ++j, ++state_id)
3620 if (context->dirty_compute_states[i] & (1u << j))
3621 state_table[state_id].apply(context, state, state_id);
3624 memset(context->dirty_compute_states, 0, sizeof(*context->dirty_compute_states));
3626 if (context->shader_update_mask & (1u << WINED3D_SHADER_TYPE_COMPUTE))
3628 device->shader_backend->shader_select_compute(device->shader_priv, context, state);
3629 context->shader_update_mask &= ~(1u << WINED3D_SHADER_TYPE_COMPUTE);
3632 if (context->update_compute_shader_resource_bindings)
3634 unsigned int base_idx, count;
3635 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits,
3636 WINED3D_SHADER_TYPE_COMPUTE, &base_idx, &count);
3637 context_bind_shader_resources(context, state, WINED3D_SHADER_TYPE_COMPUTE, base_idx, count);
3638 context->update_compute_shader_resource_bindings = 0;
3639 if (gl_info->limits.combined_samplers == gl_info->limits.graphics_samplers)
3640 context->update_shader_resource_bindings = 1;
3643 if (context->update_compute_unordered_access_view_bindings)
3645 context_bind_unordered_access_views(context,
3646 state->shader[WINED3D_SHADER_TYPE_COMPUTE],
3647 state->unordered_access_view[WINED3D_PIPELINE_COMPUTE]);
3648 context->update_compute_unordered_access_view_bindings = 0;
3649 context->update_unordered_access_view_bindings = 1;
3652 context->last_was_blit = FALSE;
3655 static void context_setup_target(struct wined3d_context *context,
3656 struct wined3d_texture *texture, unsigned int sub_resource_idx)
3658 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
3660 render_offscreen = wined3d_resource_is_offscreen(&texture->resource);
3661 if (context->current_rt.texture == texture
3662 && context->current_rt.sub_resource_idx == sub_resource_idx
3663 && render_offscreen == old_render_offscreen)
3664 return;
3666 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
3667 * the alpha blend state changes with different render target formats. */
3668 if (!context->current_rt.texture)
3670 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3672 else
3674 const struct wined3d_format *old = context->current_rt.texture->resource.format;
3675 const struct wined3d_format *new = texture->resource.format;
3677 if (old->id != new->id)
3679 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
3680 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
3681 || !(texture->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
3682 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3684 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
3685 if ((context->current_rt.texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
3686 != (texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
3687 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3690 /* When switching away from an offscreen render target, and we're not
3691 * using FBOs, we have to read the drawable into the texture. This is
3692 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
3693 * There are some things that need care though. PreLoad needs a GL context,
3694 * and FindContext is called before the context is activated. It also
3695 * has to be called with the old rendertarget active, otherwise a
3696 * wrong drawable is read. */
3697 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
3698 && old_render_offscreen && (context->current_rt.texture != texture
3699 || context->current_rt.sub_resource_idx != sub_resource_idx))
3701 unsigned int prev_sub_resource_idx = context->current_rt.sub_resource_idx;
3702 struct wined3d_texture *prev_texture = context->current_rt.texture;
3704 /* Read the back buffer of the old drawable into the destination texture. */
3705 if (prev_texture->texture_srgb.name)
3706 wined3d_texture_load(prev_texture, context, TRUE);
3707 wined3d_texture_load(prev_texture, context, FALSE);
3708 wined3d_texture_invalidate_location(prev_texture, prev_sub_resource_idx, WINED3D_LOCATION_DRAWABLE);
3712 context->current_rt.texture = texture;
3713 context->current_rt.sub_resource_idx = sub_resource_idx;
3714 context_set_render_offscreen(context, render_offscreen);
3717 struct wined3d_context *context_acquire(const struct wined3d_device *device,
3718 struct wined3d_texture *texture, unsigned int sub_resource_idx)
3720 struct wined3d_context *current_context = context_get_current();
3721 struct wined3d_context *context;
3723 TRACE("device %p, texture %p, sub_resource_idx %u.\n", device, texture, sub_resource_idx);
3725 if (current_context && current_context->destroyed)
3726 current_context = NULL;
3728 if (!texture)
3730 if (current_context
3731 && current_context->current_rt.texture
3732 && current_context->device == device)
3734 texture = current_context->current_rt.texture;
3735 sub_resource_idx = current_context->current_rt.sub_resource_idx;
3737 else
3739 struct wined3d_swapchain *swapchain = device->swapchains[0];
3741 if (swapchain->back_buffers)
3742 texture = swapchain->back_buffers[0];
3743 else
3744 texture = swapchain->front_buffer;
3745 sub_resource_idx = 0;
3749 if (current_context && current_context->current_rt.texture == texture)
3751 context = current_context;
3753 else if (texture->swapchain)
3755 TRACE("Rendering onscreen.\n");
3757 context = swapchain_get_context(texture->swapchain);
3759 else
3761 TRACE("Rendering offscreen.\n");
3763 /* Stay with the current context if possible. Otherwise use the
3764 * context for the primary swapchain. */
3765 if (current_context && current_context->device == device)
3766 context = current_context;
3767 else
3768 context = swapchain_get_context(device->swapchains[0]);
3771 context_enter(context);
3772 context_update_window(context);
3773 context_setup_target(context, texture, sub_resource_idx);
3774 if (!context->valid) return context;
3776 if (context != current_context)
3778 if (!context_set_current(context))
3779 ERR("Failed to activate the new context.\n");
3781 else if (context->needs_set)
3783 context_set_gl_context(context);
3786 return context;