webservices: Add support for union types in the writer.
[wine.git] / dlls / wined3d / context.c
blobfbc73ca9a1ec03968c0752e17527bae52a6dff6b
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
37 #define WINED3D_ALL_LAYERS (~0u)
39 static DWORD wined3d_context_tls_idx;
41 /* FBO helper functions */
43 /* Context activation is done by the caller. */
44 static void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint fbo)
46 const struct wined3d_gl_info *gl_info = context->gl_info;
48 switch (target)
50 case GL_READ_FRAMEBUFFER:
51 if (context->fbo_read_binding == fbo) return;
52 context->fbo_read_binding = fbo;
53 break;
55 case GL_DRAW_FRAMEBUFFER:
56 if (context->fbo_draw_binding == fbo) return;
57 context->fbo_draw_binding = fbo;
58 break;
60 case GL_FRAMEBUFFER:
61 if (context->fbo_read_binding == fbo
62 && context->fbo_draw_binding == fbo) return;
63 context->fbo_read_binding = fbo;
64 context->fbo_draw_binding = fbo;
65 break;
67 default:
68 FIXME("Unhandled target %#x.\n", target);
69 break;
72 gl_info->fbo_ops.glBindFramebuffer(target, fbo);
73 checkGLcall("glBindFramebuffer()");
76 /* Context activation is done by the caller. */
77 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info, GLenum target)
79 unsigned int i;
81 for (i = 0; i < gl_info->limits.buffers; ++i)
83 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
84 checkGLcall("glFramebufferTexture2D()");
86 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
87 checkGLcall("glFramebufferTexture2D()");
89 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
90 checkGLcall("glFramebufferTexture2D()");
93 /* Context activation is done by the caller. */
94 static void context_destroy_fbo(struct wined3d_context *context, GLuint fbo)
96 const struct wined3d_gl_info *gl_info = context->gl_info;
98 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
99 context_clean_fbo_attachments(gl_info, GL_FRAMEBUFFER);
100 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
102 gl_info->fbo_ops.glDeleteFramebuffers(1, &fbo);
103 checkGLcall("glDeleteFramebuffers()");
106 static void context_attach_depth_stencil_rb(const struct wined3d_gl_info *gl_info,
107 GLenum fbo_target, DWORD flags, GLuint rb)
109 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
111 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
112 checkGLcall("glFramebufferRenderbuffer()");
115 if (flags & WINED3D_FBO_ENTRY_FLAG_STENCIL)
117 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb);
118 checkGLcall("glFramebufferRenderbuffer()");
122 static void context_attach_gl_texture_fbo(struct wined3d_context *context,
123 GLenum fbo_target, GLenum attachment, const struct wined3d_fbo_resource *resource)
125 const struct wined3d_gl_info *gl_info = context->gl_info;
127 if (!resource)
129 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, attachment, GL_TEXTURE_2D, 0, 0);
131 else if (resource->layer == WINED3D_ALL_LAYERS)
133 if (!gl_info->fbo_ops.glFramebufferTexture)
135 FIXME("OpenGL implementation doesn't support glFramebufferTexture().\n");
136 return;
139 gl_info->fbo_ops.glFramebufferTexture(fbo_target, attachment,
140 resource->object, resource->level);
142 else if (resource->target == GL_TEXTURE_2D_ARRAY || resource->target == GL_TEXTURE_3D)
144 if (!gl_info->fbo_ops.glFramebufferTextureLayer)
146 FIXME("OpenGL implementation doesn't support glFramebufferTextureLayer().\n");
147 return;
150 gl_info->fbo_ops.glFramebufferTextureLayer(fbo_target, attachment,
151 resource->object, resource->level, resource->layer);
153 else
155 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, attachment,
156 resource->target, resource->object, resource->level);
158 checkGLcall("attach texture to fbo");
161 /* Context activation is done by the caller. */
162 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
163 GLenum fbo_target, const struct wined3d_fbo_resource *resource, BOOL rb_namespace,
164 DWORD flags)
166 const struct wined3d_gl_info *gl_info = context->gl_info;
168 if (resource->object)
170 TRACE("Attach depth stencil %u.\n", resource->object);
172 if (rb_namespace)
174 context_attach_depth_stencil_rb(gl_info, fbo_target,
175 flags, resource->object);
177 else
179 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
180 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, resource);
182 if (flags & WINED3D_FBO_ENTRY_FLAG_STENCIL)
183 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, resource);
186 if (!(flags & WINED3D_FBO_ENTRY_FLAG_DEPTH))
187 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, NULL);
189 if (!(flags & WINED3D_FBO_ENTRY_FLAG_STENCIL))
190 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, NULL);
192 else
194 TRACE("Attach depth stencil 0.\n");
196 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, NULL);
197 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, NULL);
201 /* Context activation is done by the caller. */
202 static void context_attach_surface_fbo(struct wined3d_context *context,
203 GLenum fbo_target, DWORD idx, const struct wined3d_fbo_resource *resource, BOOL rb_namespace)
205 const struct wined3d_gl_info *gl_info = context->gl_info;
207 TRACE("Attach GL object %u to %u.\n", resource->object, idx);
209 if (resource->object)
212 if (rb_namespace)
214 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
215 GL_RENDERBUFFER, resource->object);
216 checkGLcall("glFramebufferRenderbuffer()");
218 else
220 context_attach_gl_texture_fbo(context, fbo_target, GL_COLOR_ATTACHMENT0 + idx, resource);
223 else
225 context_attach_gl_texture_fbo(context, fbo_target, GL_COLOR_ATTACHMENT0 + idx, NULL);
229 static void context_dump_fbo_attachment(const struct wined3d_gl_info *gl_info, GLenum target,
230 GLenum attachment)
232 static const struct
234 GLenum target;
235 GLenum binding;
236 const char *str;
237 enum wined3d_gl_extension extension;
239 texture_type[] =
241 {GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D, "2d", WINED3D_GL_EXT_NONE},
242 {GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_BINDING_RECTANGLE_ARB, "rectangle", ARB_TEXTURE_RECTANGLE},
243 {GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BINDING_2D_ARRAY, "2d-array", EXT_TEXTURE_ARRAY},
246 GLint type, name, samples, width, height, old_texture, level, face, fmt, tex_target;
248 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
249 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &name);
250 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
251 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);
253 if (type == GL_RENDERBUFFER)
255 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, name);
256 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
257 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
258 if (gl_info->limits.samples > 1)
259 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
260 else
261 samples = 1;
262 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &fmt);
263 FIXME(" %s: renderbuffer %d, %dx%d, %d samples, format %#x.\n",
264 debug_fboattachment(attachment), name, width, height, samples, fmt);
266 else if (type == GL_TEXTURE)
268 const char *tex_type_str;
270 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
271 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &level);
272 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
273 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, &face);
275 if (face)
277 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &old_texture);
279 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, name);
280 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(face, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
281 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(face, level, GL_TEXTURE_WIDTH, &width);
282 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(face, level, GL_TEXTURE_HEIGHT, &height);
284 tex_target = GL_TEXTURE_CUBE_MAP;
285 tex_type_str = "cube";
287 else
289 unsigned int i;
291 tex_type_str = NULL;
292 for (i = 0; i < sizeof(texture_type) / sizeof(*texture_type); ++i)
294 if (!gl_info->supported[texture_type[i].extension])
295 continue;
297 gl_info->gl_ops.gl.p_glGetIntegerv(texture_type[i].binding, &old_texture);
298 while (gl_info->gl_ops.gl.p_glGetError());
300 gl_info->gl_ops.gl.p_glBindTexture(texture_type[i].target, name);
301 if (!gl_info->gl_ops.gl.p_glGetError())
303 tex_target = texture_type[i].target;
304 tex_type_str = texture_type[i].str;
305 break;
307 gl_info->gl_ops.gl.p_glBindTexture(texture_type[i].target, old_texture);
309 if (!tex_type_str)
311 FIXME("Cannot find type of texture %d.\n", name);
312 return;
315 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
316 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_WIDTH, &width);
317 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_HEIGHT, &height);
320 FIXME(" %s: %s texture %d, %dx%d, format %#x.\n", debug_fboattachment(attachment),
321 tex_type_str, name, width, height, fmt);
323 gl_info->gl_ops.gl.p_glBindTexture(tex_target, old_texture);
324 checkGLcall("Guess texture type");
326 else if (type == GL_NONE)
328 FIXME(" %s: NONE.\n", debug_fboattachment(attachment));
330 else
332 ERR(" %s: Unknown attachment %#x.\n", debug_fboattachment(attachment), type);
336 /* Context activation is done by the caller. */
337 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
339 const struct wined3d_gl_info *gl_info = context->gl_info;
340 GLenum status;
342 if (!FIXME_ON(d3d)) return;
344 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
345 if (status == GL_FRAMEBUFFER_COMPLETE)
347 TRACE("FBO complete\n");
349 else
351 unsigned int i;
353 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
355 if (!context->current_fbo)
357 ERR("FBO 0 is incomplete, driver bug?\n");
358 return;
361 context_dump_fbo_attachment(gl_info, target, GL_DEPTH_ATTACHMENT);
362 context_dump_fbo_attachment(gl_info, target, GL_STENCIL_ATTACHMENT);
364 for (i = 0; i < gl_info->limits.buffers; ++i)
365 context_dump_fbo_attachment(gl_info, target, GL_COLOR_ATTACHMENT0 + i);
366 checkGLcall("Dump FBO attachments");
370 static inline DWORD context_generate_rt_mask(GLenum buffer)
372 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
373 return buffer ? (1u << 31) | buffer : 0;
376 static inline DWORD context_generate_rt_mask_from_resource(struct wined3d_resource *resource)
378 if (resource->type != WINED3D_RTYPE_TEXTURE_2D)
380 FIXME("Not implemented for %s resources.\n", debug_d3dresourcetype(resource->type));
381 return 0;
384 return (1u << 31) | wined3d_texture_get_gl_buffer(texture_from_resource(resource));
387 static inline void context_set_fbo_key_for_render_target(const struct wined3d_context *context,
388 struct wined3d_fbo_entry_key *key, unsigned int idx, struct wined3d_rendertarget_info *render_target,
389 DWORD location)
391 unsigned int sub_resource_idx = render_target->sub_resource_idx;
392 struct wined3d_resource *resource = render_target->resource;
393 struct wined3d_texture *texture;
395 if (!resource || resource->format->id == WINED3DFMT_NULL || resource->type == WINED3D_RTYPE_BUFFER)
397 if (resource && resource->type == WINED3D_RTYPE_BUFFER)
398 FIXME("Not implemented for %s resources.\n", debug_d3dresourcetype(resource->type));
399 key->objects[idx].object = 0;
400 key->objects[idx].target = 0;
401 key->objects[idx].level = key->objects[idx].layer = 0;
402 return;
405 if (render_target->gl_view.name)
407 key->objects[idx].object = render_target->gl_view.name;
408 key->objects[idx].target = render_target->gl_view.target;
409 key->objects[idx].level = 0;
410 key->objects[idx].layer = WINED3D_ALL_LAYERS;
411 return;
414 texture = wined3d_texture_from_resource(resource);
415 if (resource->type == WINED3D_RTYPE_TEXTURE_2D)
417 struct wined3d_surface *surface = texture->sub_resources[sub_resource_idx].u.surface;
419 if (surface->current_renderbuffer)
421 key->objects[idx].object = surface->current_renderbuffer->id;
422 key->objects[idx].target = 0;
423 key->objects[idx].level = key->objects[idx].layer = 0;
424 key->rb_namespace |= 1 << idx;
425 return;
428 key->objects[idx].target = surface->texture_target;
429 key->objects[idx].level = surface->texture_level;
430 key->objects[idx].layer = surface->texture_layer;
432 else
434 key->objects[idx].target = texture->target;
435 key->objects[idx].level = sub_resource_idx % texture->level_count;
436 key->objects[idx].layer = sub_resource_idx / texture->level_count;
438 if (render_target->layer_count != 1)
439 key->objects[idx].layer = WINED3D_ALL_LAYERS;
441 switch (location)
443 case WINED3D_LOCATION_TEXTURE_RGB:
444 key->objects[idx].object = wined3d_texture_get_texture_name(texture, context, FALSE);
445 break;
447 case WINED3D_LOCATION_TEXTURE_SRGB:
448 key->objects[idx].object = wined3d_texture_get_texture_name(texture, context, TRUE);
449 break;
451 case WINED3D_LOCATION_RB_MULTISAMPLE:
452 key->objects[idx].object = texture->rb_multisample;
453 key->objects[idx].target = 0;
454 key->objects[idx].level = key->objects[idx].layer = 0;
455 key->rb_namespace |= 1 << idx;
456 break;
458 case WINED3D_LOCATION_RB_RESOLVED:
459 key->objects[idx].object = texture->rb_resolved;
460 key->objects[idx].target = 0;
461 key->objects[idx].level = key->objects[idx].layer = 0;
462 key->rb_namespace |= 1 << idx;
463 break;
467 static void context_generate_fbo_key(const struct wined3d_context *context,
468 struct wined3d_fbo_entry_key *key, struct wined3d_rendertarget_info *render_targets,
469 struct wined3d_surface *depth_stencil_surface, DWORD color_location,
470 DWORD ds_location)
472 struct wined3d_rendertarget_info depth_stencil = {{0}};
473 unsigned int i;
475 key->rb_namespace = 0;
476 if (depth_stencil_surface)
478 depth_stencil.resource = &depth_stencil_surface->container->resource;
479 depth_stencil.sub_resource_idx = surface_get_sub_resource_idx(depth_stencil_surface);
480 depth_stencil.layer_count = 1;
482 context_set_fbo_key_for_render_target(context, key, 0, &depth_stencil, ds_location);
484 for (i = 0; i < context->gl_info->limits.buffers; ++i)
485 context_set_fbo_key_for_render_target(context, key, i + 1, &render_targets[i], color_location);
488 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
489 struct wined3d_rendertarget_info *render_targets, struct wined3d_surface *depth_stencil,
490 DWORD color_location, DWORD ds_location)
492 const struct wined3d_gl_info *gl_info = context->gl_info;
493 unsigned int object_count = gl_info->limits.buffers + 1;
494 struct fbo_entry *entry;
496 entry = HeapAlloc(GetProcessHeap(), 0,
497 FIELD_OFFSET(struct fbo_entry, key.objects[object_count]));
498 memset(&entry->key, 0, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count]));
499 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
500 entry->flags = 0;
501 if (depth_stencil)
503 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
504 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
505 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
506 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
508 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
509 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
510 checkGLcall("glGenFramebuffers()");
511 TRACE("Created FBO %u.\n", entry->id);
513 return entry;
516 /* Context activation is done by the caller. */
517 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
518 struct wined3d_rendertarget_info *render_targets, struct wined3d_surface *depth_stencil,
519 DWORD color_location, DWORD ds_location, struct fbo_entry *entry)
521 const struct wined3d_gl_info *gl_info = context->gl_info;
523 context_bind_fbo(context, target, entry->id);
524 context_clean_fbo_attachments(gl_info, target);
526 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
527 entry->flags = 0;
528 if (depth_stencil)
530 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
531 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
532 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
533 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
537 /* Context activation is done by the caller. */
538 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
540 if (entry->id)
542 TRACE("Destroy FBO %u.\n", entry->id);
543 context_destroy_fbo(context, entry->id);
545 --context->fbo_entry_count;
546 list_remove(&entry->entry);
547 HeapFree(GetProcessHeap(), 0, entry);
550 /* Context activation is done by the caller. */
551 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
552 struct wined3d_rendertarget_info *render_targets, struct wined3d_surface *depth_stencil,
553 DWORD color_location, DWORD ds_location)
555 const struct wined3d_gl_info *gl_info = context->gl_info;
556 unsigned int object_count = gl_info->limits.buffers + 1;
557 struct wined3d_texture *rt_texture, *ds_texture;
558 struct fbo_entry *entry;
559 unsigned int i, level;
561 if (depth_stencil && render_targets[0].resource && render_targets[0].resource->type != WINED3D_RTYPE_BUFFER)
563 rt_texture = wined3d_texture_from_resource(render_targets[0].resource);
564 level = render_targets[0].sub_resource_idx % rt_texture->level_count;
565 ds_texture = depth_stencil->container;
567 if (wined3d_texture_get_level_width(ds_texture, depth_stencil->texture_level)
568 < wined3d_texture_get_level_width(rt_texture, level)
569 || wined3d_texture_get_level_height(ds_texture, depth_stencil->texture_level)
570 < wined3d_texture_get_level_height(rt_texture, level))
572 WARN("Depth stencil is smaller than the primary color buffer, disabling.\n");
573 depth_stencil = NULL;
575 else if (ds_texture->resource.multisample_type != rt_texture->resource.multisample_type
576 || ds_texture->resource.multisample_quality != rt_texture->resource.multisample_quality)
578 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
579 rt_texture->resource.multisample_type, rt_texture->resource.multisample_quality,
580 ds_texture->resource.multisample_type, ds_texture->resource.multisample_quality);
581 depth_stencil = NULL;
583 else
584 surface_set_compatible_renderbuffer(depth_stencil, &render_targets[0]);
587 context_generate_fbo_key(context, context->fbo_key, render_targets, depth_stencil, color_location,
588 ds_location);
590 if (TRACE_ON(d3d))
592 TRACE("Dumping FBO attachments:\n");
593 for (i = 0; i < gl_info->limits.buffers; ++i)
595 struct wined3d_resource *resource;
596 if ((resource = render_targets[i].resource))
598 unsigned int width, height;
599 const char *resource_type;
601 if (resource->type == WINED3D_RTYPE_BUFFER)
603 width = resource->size;
604 height = 1;
605 resource_type = "buffer";
607 else
609 rt_texture = wined3d_texture_from_resource(resource);
610 level = render_targets[i].sub_resource_idx % rt_texture->level_count;
611 width = wined3d_texture_get_level_pow2_width(rt_texture, level);
612 height = wined3d_texture_get_level_pow2_height(rt_texture, level);
613 resource_type = "texture";
616 TRACE(" Color attachment %u: %p, %u format %s, %s %u, %ux%u, %u samples.\n",
617 i, resource, render_targets[i].sub_resource_idx, debug_d3dformat(resource->format->id),
618 context->fbo_key->rb_namespace & (1 << (i + 1)) ? "renderbuffer" : resource_type,
619 context->fbo_key->objects[i + 1].object, width, height, resource->multisample_type);
622 if (depth_stencil)
624 ds_texture = depth_stencil->container;
625 TRACE(" Depth attachment: %p format %s, %s %u, %ux%u, %u samples.\n",
626 depth_stencil, debug_d3dformat(ds_texture->resource.format->id),
627 context->fbo_key->rb_namespace & (1 << 0) ? "renderbuffer" : "texture",
628 context->fbo_key->objects[0].object,
629 wined3d_texture_get_level_pow2_width(ds_texture, depth_stencil->texture_level),
630 wined3d_texture_get_level_pow2_height(ds_texture, depth_stencil->texture_level),
631 ds_texture->resource.multisample_type);
635 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
637 if (memcmp(context->fbo_key, &entry->key, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count])))
638 continue;
640 list_remove(&entry->entry);
641 list_add_head(&context->fbo_list, &entry->entry);
642 return entry;
645 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
647 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
648 list_add_head(&context->fbo_list, &entry->entry);
649 ++context->fbo_entry_count;
651 else
653 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
654 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
655 list_remove(&entry->entry);
656 list_add_head(&context->fbo_list, &entry->entry);
659 return entry;
662 /* Context activation is done by the caller. */
663 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
665 const struct wined3d_gl_info *gl_info = context->gl_info;
666 unsigned int i;
667 GLuint read_binding, draw_binding;
669 if (entry->flags & WINED3D_FBO_ENTRY_FLAG_ATTACHED)
671 context_bind_fbo(context, target, entry->id);
672 return;
675 read_binding = context->fbo_read_binding;
676 draw_binding = context->fbo_draw_binding;
677 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
679 /* Apply render targets */
680 for (i = 0; i < gl_info->limits.buffers; ++i)
682 context_attach_surface_fbo(context, target, i, &entry->key.objects[i + 1],
683 entry->key.rb_namespace & (1 << (i + 1)));
686 context_attach_depth_stencil_fbo(context, target, &entry->key.objects[0],
687 entry->key.rb_namespace & 0x1, entry->flags);
689 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
690 * GL contexts requirements. */
691 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
692 context_set_draw_buffer(context, GL_NONE);
693 if (target != GL_FRAMEBUFFER)
695 if (target == GL_READ_FRAMEBUFFER)
696 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
697 else
698 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
701 entry->flags |= WINED3D_FBO_ENTRY_FLAG_ATTACHED;
704 /* Context activation is done by the caller. */
705 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
706 struct wined3d_rendertarget_info *render_targets, struct wined3d_surface *depth_stencil,
707 DWORD color_location, DWORD ds_location)
709 struct fbo_entry *entry, *entry2;
711 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
713 context_destroy_fbo_entry(context, entry);
716 if (context->rebind_fbo)
718 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
719 context->rebind_fbo = FALSE;
722 if (color_location == WINED3D_LOCATION_DRAWABLE)
724 context->current_fbo = NULL;
725 context_bind_fbo(context, target, 0);
727 else
729 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
730 color_location, ds_location);
731 context_apply_fbo_entry(context, target, context->current_fbo);
735 /* Context activation is done by the caller. */
736 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
737 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
739 memset(context->blit_targets, 0, context->gl_info->limits.buffers * sizeof(*context->blit_targets));
740 if (render_target)
742 context->blit_targets[0].resource = &render_target->container->resource;
743 context->blit_targets[0].sub_resource_idx = surface_get_sub_resource_idx(render_target);
744 context->blit_targets[0].layer_count = 1;
746 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
749 /* Context activation is done by the caller. */
750 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
752 const struct wined3d_gl_info *gl_info = context->gl_info;
754 if (context->free_occlusion_query_count)
756 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
758 else
760 if (gl_info->supported[ARB_OCCLUSION_QUERY])
762 GL_EXTCALL(glGenQueries(1, &query->id));
763 checkGLcall("glGenQueries");
765 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
767 else
769 WARN("Occlusion queries not supported, not allocating query id.\n");
770 query->id = 0;
774 query->context = context;
775 list_add_head(&context->occlusion_queries, &query->entry);
778 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
780 struct wined3d_context *context = query->context;
782 list_remove(&query->entry);
783 query->context = NULL;
785 if (!wined3d_array_reserve((void **)&context->free_occlusion_queries,
786 &context->free_occlusion_query_size, context->free_occlusion_query_count + 1,
787 sizeof(*context->free_occlusion_queries)))
789 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
790 return;
793 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
796 /* Context activation is done by the caller. */
797 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
799 const struct wined3d_gl_info *gl_info = context->gl_info;
801 if (context->free_event_query_count)
803 query->object = context->free_event_queries[--context->free_event_query_count];
805 else
807 if (gl_info->supported[ARB_SYNC])
809 /* Using ARB_sync, not much to do here. */
810 query->object.sync = NULL;
811 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
813 else if (gl_info->supported[APPLE_FENCE])
815 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
816 checkGLcall("glGenFencesAPPLE");
818 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
820 else if(gl_info->supported[NV_FENCE])
822 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
823 checkGLcall("glGenFencesNV");
825 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
827 else
829 WARN("Event queries not supported, not allocating query id.\n");
830 query->object.id = 0;
834 query->context = context;
835 list_add_head(&context->event_queries, &query->entry);
838 void context_free_event_query(struct wined3d_event_query *query)
840 struct wined3d_context *context = query->context;
842 list_remove(&query->entry);
843 query->context = NULL;
845 if (!wined3d_array_reserve((void **)&context->free_event_queries,
846 &context->free_event_query_size, context->free_event_query_count + 1,
847 sizeof(*context->free_event_queries)))
849 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
850 return;
853 context->free_event_queries[context->free_event_query_count++] = query->object;
856 /* Context activation is done by the caller. */
857 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
859 const struct wined3d_gl_info *gl_info = context->gl_info;
861 if (context->free_timestamp_query_count)
863 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
865 else
867 GL_EXTCALL(glGenQueries(1, &query->id));
868 checkGLcall("glGenQueries");
870 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
873 query->context = context;
874 list_add_head(&context->timestamp_queries, &query->entry);
877 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
879 struct wined3d_context *context = query->context;
881 list_remove(&query->entry);
882 query->context = NULL;
884 if (!wined3d_array_reserve((void **)&context->free_timestamp_queries,
885 &context->free_timestamp_query_size, context->free_timestamp_query_count + 1,
886 sizeof(*context->free_timestamp_queries)))
888 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
889 return;
892 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
895 void context_alloc_so_statistics_query(struct wined3d_context *context,
896 struct wined3d_so_statistics_query *query)
898 const struct wined3d_gl_info *gl_info = context->gl_info;
900 if (context->free_so_statistics_query_count)
902 query->u = context->free_so_statistics_queries[--context->free_so_statistics_query_count];
904 else
906 GL_EXTCALL(glGenQueries(ARRAY_SIZE(query->u.id), query->u.id));
907 checkGLcall("glGenQueries");
909 TRACE("Allocated SO statistics queries %u, %u in context %p.\n",
910 query->u.id[0], query->u.id[1], context);
913 query->context = context;
914 list_add_head(&context->so_statistics_queries, &query->entry);
917 void context_free_so_statistics_query(struct wined3d_so_statistics_query *query)
919 struct wined3d_context *context = query->context;
921 list_remove(&query->entry);
922 query->context = NULL;
924 if (!wined3d_array_reserve((void **)&context->free_so_statistics_queries,
925 &context->free_so_statistics_query_size, context->free_so_statistics_query_count + 1,
926 sizeof(*context->free_so_statistics_queries)))
928 ERR("Failed to grow free list, leaking GL queries %u, %u in context %p.\n",
929 query->u.id[0], query->u.id[1], context);
930 return;
933 context->free_so_statistics_queries[context->free_so_statistics_query_count++] = query->u;
936 void context_alloc_pipeline_statistics_query(struct wined3d_context *context,
937 struct wined3d_pipeline_statistics_query *query)
939 const struct wined3d_gl_info *gl_info = context->gl_info;
941 if (context->free_pipeline_statistics_query_count)
943 query->u = context->free_pipeline_statistics_queries[--context->free_pipeline_statistics_query_count];
945 else
947 GL_EXTCALL(glGenQueries(ARRAY_SIZE(query->u.id), query->u.id));
948 checkGLcall("glGenQueries");
951 query->context = context;
952 list_add_head(&context->pipeline_statistics_queries, &query->entry);
955 void context_free_pipeline_statistics_query(struct wined3d_pipeline_statistics_query *query)
957 struct wined3d_context *context = query->context;
959 list_remove(&query->entry);
960 query->context = NULL;
962 if (!wined3d_array_reserve((void **)&context->free_pipeline_statistics_queries,
963 &context->free_pipeline_statistics_query_size, context->free_pipeline_statistics_query_count + 1,
964 sizeof(*context->free_pipeline_statistics_queries)))
966 ERR("Failed to grow free list, leaking GL queries in context %p.\n", context);
967 return;
970 context->free_pipeline_statistics_queries[context->free_pipeline_statistics_query_count++] = query->u;
973 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
975 static void context_enum_fbo_entries(const struct wined3d_device *device,
976 GLuint name, BOOL rb_namespace, context_fbo_entry_func_t *callback)
978 UINT i;
980 for (i = 0; i < device->context_count; ++i)
982 struct wined3d_context *context = device->contexts[i];
983 const struct wined3d_gl_info *gl_info = context->gl_info;
984 struct fbo_entry *entry, *entry2;
986 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
988 UINT j;
990 for (j = 0; j < gl_info->limits.buffers + 1; ++j)
992 if (entry->key.objects[j].object == name
993 && !(entry->key.rb_namespace & (1 << j)) == !rb_namespace)
995 callback(context, entry);
996 break;
1003 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
1005 list_remove(&entry->entry);
1006 list_add_head(&context->fbo_destroy_list, &entry->entry);
1009 void context_resource_released(const struct wined3d_device *device,
1010 struct wined3d_resource *resource, enum wined3d_resource_type type)
1012 struct wined3d_texture *texture;
1013 UINT i;
1015 if (!device->d3d_initialized)
1016 return;
1018 switch (type)
1020 case WINED3D_RTYPE_TEXTURE_2D:
1021 case WINED3D_RTYPE_TEXTURE_3D:
1022 texture = texture_from_resource(resource);
1024 for (i = 0; i < device->context_count; ++i)
1026 struct wined3d_context *context = device->contexts[i];
1027 if (context->current_rt.texture == texture)
1029 context->current_rt.texture = NULL;
1030 context->current_rt.sub_resource_idx = 0;
1033 break;
1035 default:
1036 break;
1040 void context_gl_resource_released(struct wined3d_device *device,
1041 GLuint name, BOOL rb_namespace)
1043 context_enum_fbo_entries(device, name, rb_namespace, context_queue_fbo_entry_destruction);
1046 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
1048 const struct wined3d_gl_info *gl_info = context->gl_info;
1049 struct fbo_entry *entry = context->current_fbo;
1050 unsigned int i;
1052 if (!entry || context->rebind_fbo) return;
1054 for (i = 0; i < gl_info->limits.buffers + 1; ++i)
1056 if (surface->container->texture_rgb.name == entry->key.objects[i].object
1057 || surface->container->texture_srgb.name == entry->key.objects[i].object)
1059 TRACE("Updated surface %p is bound as attachment %u to the current FBO.\n", surface, i);
1060 context->rebind_fbo = TRUE;
1061 return;
1066 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
1068 const struct wined3d_gl_info *gl_info = ctx->gl_info;
1069 BOOL ret = FALSE;
1071 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
1073 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
1075 HDC dc = GetDCEx(ctx->restore_pf_win, 0, DCX_USESTYLE | DCX_CACHE);
1076 if (dc)
1078 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
1080 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
1081 ctx->restore_pf, ctx->restore_pf_win);
1083 ReleaseDC(ctx->restore_pf_win, dc);
1086 else
1088 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
1092 ctx->restore_pf = 0;
1093 ctx->restore_pf_win = NULL;
1094 return ret;
1097 static BOOL context_set_pixel_format(struct wined3d_context *context, HDC dc, BOOL private, int format)
1099 const struct wined3d_gl_info *gl_info = context->gl_info;
1100 int current;
1102 if (dc == context->hdc && context->hdc_is_private && context->hdc_has_format)
1103 return TRUE;
1105 current = gl_info->gl_ops.wgl.p_wglGetPixelFormat(dc);
1106 if (current == format) goto success;
1108 if (!current)
1110 if (!SetPixelFormat(dc, format, NULL))
1112 /* This may also happen if the dc belongs to a destroyed window. */
1113 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
1114 format, dc, GetLastError());
1115 return FALSE;
1118 context->restore_pf = 0;
1119 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
1120 goto success;
1123 /* By default WGL doesn't allow pixel format adjustments but we need it
1124 * here. For this reason there's a Wine specific wglSetPixelFormat()
1125 * which allows us to set the pixel format multiple times. Only use it
1126 * when really needed. */
1127 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
1129 HWND win;
1131 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
1133 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
1134 format, dc);
1135 return FALSE;
1138 win = private ? NULL : WindowFromDC(dc);
1139 if (win != context->restore_pf_win)
1141 context_restore_pixel_format(context);
1143 context->restore_pf = private ? 0 : current;
1144 context->restore_pf_win = win;
1147 goto success;
1150 /* OpenGL doesn't allow pixel format adjustments. Print an error and
1151 * continue using the old format. There's a big chance that the old
1152 * format works although with a performance hit and perhaps rendering
1153 * errors. */
1154 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
1155 format, dc, current);
1156 return TRUE;
1158 success:
1159 if (dc == context->hdc && context->hdc_is_private)
1160 context->hdc_has_format = TRUE;
1161 return TRUE;
1164 static BOOL context_set_gl_context(struct wined3d_context *ctx)
1166 struct wined3d_swapchain *swapchain = ctx->swapchain;
1167 BOOL backup = FALSE;
1169 if (!context_set_pixel_format(ctx, ctx->hdc, ctx->hdc_is_private, ctx->pixel_format))
1171 WARN("Failed to set pixel format %d on device context %p.\n",
1172 ctx->pixel_format, ctx->hdc);
1173 backup = TRUE;
1176 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
1178 HDC dc;
1180 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
1181 ctx->glCtx, ctx->hdc, GetLastError());
1182 ctx->valid = 0;
1183 WARN("Trying fallback to the backup window.\n");
1185 /* FIXME: If the context is destroyed it's no longer associated with
1186 * a swapchain, so we can't use the swapchain to get a backup dc. To
1187 * make this work windowless contexts would need to be handled by the
1188 * device. */
1189 if (ctx->destroyed || !swapchain)
1191 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
1192 context_set_current(NULL);
1193 return FALSE;
1196 if (!(dc = swapchain_get_backup_dc(swapchain)))
1198 context_set_current(NULL);
1199 return FALSE;
1202 if (!context_set_pixel_format(ctx, dc, TRUE, ctx->pixel_format))
1204 ERR("Failed to set pixel format %d on device context %p.\n",
1205 ctx->pixel_format, dc);
1206 context_set_current(NULL);
1207 return FALSE;
1210 if (!wglMakeCurrent(dc, ctx->glCtx))
1212 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
1213 dc, GetLastError());
1214 context_set_current(NULL);
1215 return FALSE;
1218 ctx->valid = 1;
1220 ctx->needs_set = 0;
1221 return TRUE;
1224 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
1226 if (!wglMakeCurrent(dc, gl_ctx))
1228 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1229 gl_ctx, dc, GetLastError());
1230 context_set_current(NULL);
1234 static void context_update_window(struct wined3d_context *context)
1236 if (!context->swapchain)
1237 return;
1239 if (context->win_handle == context->swapchain->win_handle)
1240 return;
1242 TRACE("Updating context %p window from %p to %p.\n",
1243 context, context->win_handle, context->swapchain->win_handle);
1245 if (context->hdc)
1246 wined3d_release_dc(context->win_handle, context->hdc);
1248 context->win_handle = context->swapchain->win_handle;
1249 context->hdc_is_private = FALSE;
1250 context->hdc_has_format = FALSE;
1251 context->needs_set = 1;
1252 context->valid = 1;
1254 if (!(context->hdc = GetDCEx(context->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1256 ERR("Failed to get a device context for window %p.\n", context->win_handle);
1257 context->valid = 0;
1261 static void context_destroy_gl_resources(struct wined3d_context *context)
1263 struct wined3d_pipeline_statistics_query *pipeline_statistics_query;
1264 const struct wined3d_gl_info *gl_info = context->gl_info;
1265 struct wined3d_so_statistics_query *so_statistics_query;
1266 struct wined3d_timestamp_query *timestamp_query;
1267 struct wined3d_occlusion_query *occlusion_query;
1268 struct wined3d_event_query *event_query;
1269 struct fbo_entry *entry, *entry2;
1270 HGLRC restore_ctx;
1271 HDC restore_dc;
1272 unsigned int i;
1274 restore_ctx = wglGetCurrentContext();
1275 restore_dc = wglGetCurrentDC();
1277 if (restore_ctx == context->glCtx)
1278 restore_ctx = NULL;
1279 else if (context->valid)
1280 context_set_gl_context(context);
1282 LIST_FOR_EACH_ENTRY(so_statistics_query, &context->so_statistics_queries,
1283 struct wined3d_so_statistics_query, entry)
1285 if (context->valid)
1286 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(so_statistics_query->u.id), so_statistics_query->u.id));
1287 so_statistics_query->context = NULL;
1290 LIST_FOR_EACH_ENTRY(pipeline_statistics_query, &context->pipeline_statistics_queries,
1291 struct wined3d_pipeline_statistics_query, entry)
1293 if (context->valid)
1294 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(pipeline_statistics_query->u.id), pipeline_statistics_query->u.id));
1295 pipeline_statistics_query->context = NULL;
1298 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
1300 if (context->valid)
1301 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
1302 timestamp_query->context = NULL;
1305 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1307 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1308 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1309 occlusion_query->context = NULL;
1312 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
1314 if (context->valid)
1316 if (gl_info->supported[ARB_SYNC])
1318 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
1320 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
1321 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
1323 event_query->context = NULL;
1326 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1328 if (!context->valid) entry->id = 0;
1329 context_destroy_fbo_entry(context, entry);
1332 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1334 if (!context->valid) entry->id = 0;
1335 context_destroy_fbo_entry(context, entry);
1338 if (context->valid)
1340 if (context->dummy_arbfp_prog)
1342 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1345 if (gl_info->supported[WINED3D_GL_PRIMITIVE_QUERY])
1347 for (i = 0; i < context->free_so_statistics_query_count; ++i)
1349 union wined3d_gl_so_statistics_query *q = &context->free_so_statistics_queries[i];
1350 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(q->id), q->id));
1354 if (gl_info->supported[ARB_PIPELINE_STATISTICS_QUERY])
1356 for (i = 0; i < context->free_pipeline_statistics_query_count; ++i)
1358 union wined3d_gl_pipeline_statistics_query *q = &context->free_pipeline_statistics_queries[i];
1359 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(q->id), q->id));
1363 if (gl_info->supported[ARB_TIMER_QUERY])
1364 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1366 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1367 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1369 if (gl_info->supported[ARB_SYNC])
1371 for (i = 0; i < context->free_event_query_count; ++i)
1373 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
1376 else if (gl_info->supported[APPLE_FENCE])
1378 for (i = 0; i < context->free_event_query_count; ++i)
1380 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1383 else if (gl_info->supported[NV_FENCE])
1385 for (i = 0; i < context->free_event_query_count; ++i)
1387 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1391 checkGLcall("context cleanup");
1394 HeapFree(GetProcessHeap(), 0, context->free_so_statistics_queries);
1395 HeapFree(GetProcessHeap(), 0, context->free_pipeline_statistics_queries);
1396 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1397 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1398 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1400 context_restore_pixel_format(context);
1401 if (restore_ctx)
1403 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1405 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1407 ERR("Failed to disable GL context.\n");
1410 wined3d_release_dc(context->win_handle, context->hdc);
1412 if (!wglDeleteContext(context->glCtx))
1414 DWORD err = GetLastError();
1415 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1419 DWORD context_get_tls_idx(void)
1421 return wined3d_context_tls_idx;
1424 void context_set_tls_idx(DWORD idx)
1426 wined3d_context_tls_idx = idx;
1429 struct wined3d_context *context_get_current(void)
1431 return TlsGetValue(wined3d_context_tls_idx);
1434 BOOL context_set_current(struct wined3d_context *ctx)
1436 struct wined3d_context *old = context_get_current();
1438 if (old == ctx)
1440 TRACE("Already using D3D context %p.\n", ctx);
1441 return TRUE;
1444 if (old)
1446 if (old->destroyed)
1448 TRACE("Switching away from destroyed context %p.\n", old);
1449 context_destroy_gl_resources(old);
1450 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1451 HeapFree(GetProcessHeap(), 0, old);
1453 else
1455 if (wglGetCurrentContext())
1457 const struct wined3d_gl_info *gl_info = old->gl_info;
1458 TRACE("Flushing context %p before switching to %p.\n", old, ctx);
1459 gl_info->gl_ops.gl.p_glFlush();
1461 old->current = 0;
1465 if (ctx)
1467 if (!ctx->valid)
1469 ERR("Trying to make invalid context %p current\n", ctx);
1470 return FALSE;
1473 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1474 if (!context_set_gl_context(ctx))
1475 return FALSE;
1476 ctx->current = 1;
1478 else if (wglGetCurrentContext())
1480 TRACE("Clearing current D3D context.\n");
1481 if (!wglMakeCurrent(NULL, NULL))
1483 DWORD err = GetLastError();
1484 ERR("Failed to clear current GL context, last error %#x.\n", err);
1485 TlsSetValue(wined3d_context_tls_idx, NULL);
1486 return FALSE;
1490 return TlsSetValue(wined3d_context_tls_idx, ctx);
1493 void context_release(struct wined3d_context *context)
1495 TRACE("Releasing context %p, level %u.\n", context, context->level);
1497 if (WARN_ON(d3d))
1499 if (!context->level)
1500 WARN("Context %p is not active.\n", context);
1501 else if (context != context_get_current())
1502 WARN("Context %p is not the current context.\n", context);
1505 if (!--context->level)
1507 if (context_restore_pixel_format(context))
1508 context->needs_set = 1;
1509 if (context->restore_ctx)
1511 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1512 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1513 context->restore_ctx = NULL;
1514 context->restore_dc = NULL;
1517 if (context->destroy_delayed)
1519 TRACE("Destroying context %p.\n", context);
1520 context_destroy(context->device, context);
1525 /* This is used when a context for render target A is active, but a separate context is
1526 * needed to access the WGL framebuffer for render target B. Re-acquire a context for rt
1527 * A to avoid breaking caller code. */
1528 void context_restore(struct wined3d_context *context, struct wined3d_surface *restore)
1530 if (context->current_rt.texture != restore->container
1531 || context->current_rt.sub_resource_idx != surface_get_sub_resource_idx(restore))
1533 context_release(context);
1534 context = context_acquire(restore->container->resource.device,
1535 restore->container, surface_get_sub_resource_idx(restore));
1538 context_release(context);
1541 static void context_enter(struct wined3d_context *context)
1543 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1545 if (!context->level++)
1547 const struct wined3d_context *current_context = context_get_current();
1548 HGLRC current_gl = wglGetCurrentContext();
1550 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1552 TRACE("Another GL context (%p on device context %p) is already current.\n",
1553 current_gl, wglGetCurrentDC());
1554 context->restore_ctx = current_gl;
1555 context->restore_dc = wglGetCurrentDC();
1556 context->needs_set = 1;
1558 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1559 && context->pixel_format != context->gl_info->gl_ops.wgl.p_wglGetPixelFormat(context->hdc))
1560 context->needs_set = 1;
1564 void context_invalidate_compute_state(struct wined3d_context *context, DWORD state_id)
1566 DWORD representative = context->state_table[state_id].representative - STATE_COMPUTE_OFFSET;
1567 unsigned int index, shift;
1569 index = representative / (sizeof(*context->dirty_compute_states) * CHAR_BIT);
1570 shift = representative & (sizeof(*context->dirty_compute_states) * CHAR_BIT - 1);
1571 context->dirty_compute_states[index] |= (1u << shift);
1574 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1576 DWORD rep = context->state_table[state].representative;
1577 DWORD idx;
1578 BYTE shift;
1580 if (isStateDirty(context, rep)) return;
1582 context->dirtyArray[context->numDirtyEntries++] = rep;
1583 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1584 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1585 context->isStateDirty[idx] |= (1u << shift);
1588 /* This function takes care of wined3d pixel format selection. */
1589 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1590 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1591 BOOL auxBuffers)
1593 unsigned int cfg_count = device->adapter->cfg_count;
1594 unsigned int current_value;
1595 PIXELFORMATDESCRIPTOR pfd;
1596 int iPixelFormat = 0;
1597 unsigned int i;
1599 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x.\n",
1600 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1601 auxBuffers);
1603 current_value = 0;
1604 for (i = 0; i < cfg_count; ++i)
1606 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1607 unsigned int value;
1609 /* For now only accept RGBA formats. Perhaps some day we will
1610 * allow floating point formats for pbuffers. */
1611 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1612 continue;
1613 /* In window mode we need a window drawable format and double buffering. */
1614 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1615 continue;
1616 if (cfg->redSize < color_format->red_size)
1617 continue;
1618 if (cfg->greenSize < color_format->green_size)
1619 continue;
1620 if (cfg->blueSize < color_format->blue_size)
1621 continue;
1622 if (cfg->alphaSize < color_format->alpha_size)
1623 continue;
1624 if (cfg->depthSize < ds_format->depth_size)
1625 continue;
1626 if (ds_format->stencil_size && cfg->stencilSize != ds_format->stencil_size)
1627 continue;
1628 /* Check multisampling support. */
1629 if (cfg->numSamples)
1630 continue;
1632 value = 1;
1633 /* We try to locate a format which matches our requirements exactly. In case of
1634 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1635 if (cfg->depthSize == ds_format->depth_size)
1636 value += 1;
1637 if (cfg->stencilSize == ds_format->stencil_size)
1638 value += 2;
1639 if (cfg->alphaSize == color_format->alpha_size)
1640 value += 4;
1641 /* We like to have aux buffers in backbuffer mode */
1642 if (auxBuffers && cfg->auxBuffers)
1643 value += 8;
1644 if (cfg->redSize == color_format->red_size
1645 && cfg->greenSize == color_format->green_size
1646 && cfg->blueSize == color_format->blue_size)
1647 value += 16;
1649 if (value > current_value)
1651 iPixelFormat = cfg->iPixelFormat;
1652 current_value = value;
1656 if (!iPixelFormat)
1658 ERR("Trying to locate a compatible pixel format because an exact match failed.\n");
1660 memset(&pfd, 0, sizeof(pfd));
1661 pfd.nSize = sizeof(pfd);
1662 pfd.nVersion = 1;
1663 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1664 pfd.iPixelType = PFD_TYPE_RGBA;
1665 pfd.cAlphaBits = color_format->alpha_size;
1666 pfd.cColorBits = color_format->red_size + color_format->green_size
1667 + color_format->blue_size + color_format->alpha_size;
1668 pfd.cDepthBits = ds_format->depth_size;
1669 pfd.cStencilBits = ds_format->stencil_size;
1670 pfd.iLayerType = PFD_MAIN_PLANE;
1672 if (!(iPixelFormat = ChoosePixelFormat(hdc, &pfd)))
1674 /* Something is very wrong as ChoosePixelFormat() barely fails. */
1675 ERR("Can't find a suitable pixel format.\n");
1676 return 0;
1680 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s.\n",
1681 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1682 return iPixelFormat;
1685 /* Context activation is done by the caller. */
1686 void context_bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1688 const struct wined3d_gl_info *gl_info = context->gl_info;
1689 unsigned int i;
1691 for (i = 0; i < gl_info->limits.combined_samplers; ++i)
1693 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1694 checkGLcall("glActiveTexture");
1696 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_textures.tex_2d);
1698 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1699 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_textures.tex_rect);
1701 if (gl_info->supported[EXT_TEXTURE3D])
1702 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_textures.tex_3d);
1704 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1705 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_textures.tex_cube);
1707 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP_ARRAY])
1708 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, device->dummy_textures.tex_cube_array);
1710 if (gl_info->supported[EXT_TEXTURE_ARRAY])
1711 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, device->dummy_textures.tex_2d_array);
1713 if (gl_info->supported[ARB_TEXTURE_BUFFER_OBJECT])
1714 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_BUFFER, device->dummy_textures.tex_buffer);
1716 checkGLcall("Bind dummy textures");
1720 void wined3d_check_gl_call(const struct wined3d_gl_info *gl_info,
1721 const char *file, unsigned int line, const char *name)
1723 GLint err;
1725 if (gl_info->supported[ARB_DEBUG_OUTPUT] || (err = gl_info->gl_ops.gl.p_glGetError()) == GL_NO_ERROR)
1727 TRACE("%s call ok %s / %u.\n", name, file, line);
1728 return;
1733 ERR(">>>>>>> %s (%#x) from %s @ %s / %u.\n",
1734 debug_glerror(err), err, name, file,line);
1735 err = gl_info->gl_ops.gl.p_glGetError();
1736 } while (err != GL_NO_ERROR);
1739 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1741 return gl_info->supported[ARB_DEBUG_OUTPUT]
1742 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1745 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1746 GLenum severity, GLsizei length, const char *message, void *ctx)
1748 switch (type)
1750 case GL_DEBUG_TYPE_ERROR_ARB:
1751 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1752 break;
1754 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1755 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1756 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1757 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1758 break;
1760 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1761 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1762 break;
1764 default:
1765 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1766 break;
1770 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1772 HGLRC ctx;
1773 unsigned int ctx_attrib_idx = 0;
1774 GLint ctx_attribs[7], ctx_flags = 0;
1776 if (context_debug_output_enabled(gl_info))
1777 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1778 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1779 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1780 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1781 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1782 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1783 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1784 if (ctx_flags)
1786 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1787 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1789 ctx_attribs[ctx_attrib_idx] = 0;
1791 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1793 if (ctx_flags & WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
1795 ctx_attribs[ctx_attrib_idx - 1] &= ~WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1796 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1797 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1798 GetLastError());
1801 return ctx;
1804 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1805 struct wined3d_texture *target, const struct wined3d_format *ds_format)
1807 struct wined3d_device *device = swapchain->device;
1808 const struct wined3d_d3d_info *d3d_info = &device->adapter->d3d_info;
1809 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1810 const struct wined3d_format *color_format;
1811 struct wined3d_context *ret;
1812 BOOL hdc_is_private = FALSE;
1813 BOOL auxBuffers = FALSE;
1814 HGLRC ctx, share_ctx;
1815 DWORD target_usage;
1816 int pixel_format;
1817 unsigned int i;
1818 DWORD state;
1819 HDC hdc = 0;
1821 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1823 wined3d_from_cs(device->cs);
1825 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1826 if (!ret)
1827 return NULL;
1829 if (!(ret->blit_targets = wined3d_calloc(gl_info->limits.buffers, sizeof(*ret->blit_targets))))
1830 goto out;
1832 if (!(ret->draw_buffers = wined3d_calloc(gl_info->limits.buffers, sizeof(*ret->draw_buffers))))
1833 goto out;
1835 ret->fbo_key = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1836 FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[gl_info->limits.buffers + 1]));
1837 if (!ret->fbo_key)
1838 goto out;
1840 ret->free_timestamp_query_size = 4;
1841 if (!(ret->free_timestamp_queries = wined3d_calloc(ret->free_timestamp_query_size,
1842 sizeof(*ret->free_timestamp_queries))))
1843 goto out;
1844 list_init(&ret->timestamp_queries);
1846 ret->free_occlusion_query_size = 4;
1847 if (!(ret->free_occlusion_queries = wined3d_calloc(ret->free_occlusion_query_size,
1848 sizeof(*ret->free_occlusion_queries))))
1849 goto out;
1850 list_init(&ret->occlusion_queries);
1852 ret->free_event_query_size = 4;
1853 if (!(ret->free_event_queries = wined3d_calloc(ret->free_event_query_size,
1854 sizeof(*ret->free_event_queries))))
1855 goto out;
1856 list_init(&ret->event_queries);
1858 list_init(&ret->so_statistics_queries);
1860 list_init(&ret->pipeline_statistics_queries);
1862 list_init(&ret->fbo_list);
1863 list_init(&ret->fbo_destroy_list);
1865 if (!device->shader_backend->shader_allocate_context_data(ret))
1867 ERR("Failed to allocate shader backend context data.\n");
1868 goto out;
1870 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1872 ERR("Failed to allocate fragment pipeline context data.\n");
1873 goto out;
1876 for (i = 0; i < ARRAY_SIZE(ret->tex_unit_map); ++i)
1877 ret->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
1878 for (i = 0; i < ARRAY_SIZE(ret->rev_tex_unit_map); ++i)
1879 ret->rev_tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
1880 if (gl_info->limits.graphics_samplers >= MAX_COMBINED_SAMPLERS)
1882 /* Initialize the texture unit mapping to a 1:1 mapping. */
1883 unsigned int base, count;
1885 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, WINED3D_SHADER_TYPE_PIXEL, &base, &count);
1886 if (base + MAX_FRAGMENT_SAMPLERS > ARRAY_SIZE(ret->rev_tex_unit_map))
1888 ERR("Unexpected texture unit base index %u.\n", base);
1889 goto out;
1891 for (i = 0; i < min(count, MAX_FRAGMENT_SAMPLERS); ++i)
1893 ret->tex_unit_map[i] = base + i;
1894 ret->rev_tex_unit_map[base + i] = i;
1897 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, WINED3D_SHADER_TYPE_VERTEX, &base, &count);
1898 if (base + MAX_VERTEX_SAMPLERS > ARRAY_SIZE(ret->rev_tex_unit_map))
1900 ERR("Unexpected texture unit base index %u.\n", base);
1901 goto out;
1903 for (i = 0; i < min(count, MAX_VERTEX_SAMPLERS); ++i)
1905 ret->tex_unit_map[MAX_FRAGMENT_SAMPLERS + i] = base + i;
1906 ret->rev_tex_unit_map[base + i] = MAX_FRAGMENT_SAMPLERS + i;
1910 if (!(ret->texture_type = wined3d_calloc(gl_info->limits.combined_samplers,
1911 sizeof(*ret->texture_type))))
1912 goto out;
1914 if (!(hdc = GetDCEx(swapchain->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1916 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1918 if ((hdc = swapchain_get_backup_dc(swapchain)))
1919 hdc_is_private = TRUE;
1920 else
1922 ERR("Failed to retrieve a device context.\n");
1923 goto out;
1927 color_format = target->resource.format;
1928 target_usage = target->resource.usage;
1930 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1931 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1932 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1934 auxBuffers = TRUE;
1936 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1937 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM, target_usage);
1938 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1939 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1942 /* DirectDraw supports 8bit paletted render targets and these are used by
1943 * old games like StarCraft and C&C. Most modern hardware doesn't support
1944 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1945 * conversion (ab)uses the alpha component for storing the palette index.
1946 * For this reason we require a format with 8bit alpha, so request
1947 * A8R8G8B8. */
1948 if (color_format->id == WINED3DFMT_P8_UINT)
1949 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1951 /* When using FBOs for off-screen rendering, we only use the drawable for
1952 * presentation blits, and don't do any rendering to it. That means we
1953 * don't need depth or stencil buffers, and can mostly ignore the render
1954 * target format. This wouldn't necessarily be quite correct for 10bpc
1955 * display modes, but we don't currently support those.
1956 * Using the same format regardless of the color/depth/stencil targets
1957 * makes it much less likely that different wined3d instances will set
1958 * conflicting pixel formats. */
1959 if (wined3d_settings.offscreen_rendering_mode != ORM_BACKBUFFER)
1961 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1962 ds_format = wined3d_get_format(gl_info, WINED3DFMT_UNKNOWN, WINED3DUSAGE_DEPTHSTENCIL);
1965 /* Try to find a pixel format which matches our requirements. */
1966 if (!(pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers)))
1967 goto out;
1969 ret->gl_info = gl_info;
1971 context_enter(ret);
1973 if (!context_set_pixel_format(ret, hdc, hdc_is_private, pixel_format))
1975 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1976 context_release(ret);
1977 goto out;
1980 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1981 if (gl_info->p_wglCreateContextAttribsARB)
1983 if (!(ctx = context_create_wgl_attribs(gl_info, hdc, share_ctx)))
1984 goto out;
1986 else
1988 if (!(ctx = wglCreateContext(hdc)))
1990 ERR("Failed to create a WGL context.\n");
1991 context_release(ret);
1992 goto out;
1995 if (share_ctx && !wglShareLists(share_ctx, ctx))
1997 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1998 context_release(ret);
1999 if (!wglDeleteContext(ctx))
2000 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
2001 goto out;
2005 if (!device_context_add(device, ret))
2007 ERR("Failed to add the newly created context to the context list\n");
2008 context_release(ret);
2009 if (!wglDeleteContext(ctx))
2010 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
2011 goto out;
2014 ret->d3d_info = d3d_info;
2015 ret->state_table = device->StateTable;
2017 /* Mark all states dirty to force a proper initialization of the states on
2018 * the first use of the context. Compute states do not need initialization. */
2019 for (state = 0; state <= STATE_HIGHEST; ++state)
2021 if (ret->state_table[state].representative && !STATE_IS_COMPUTE(state))
2022 context_invalidate_state(ret, state);
2025 ret->device = device;
2026 ret->swapchain = swapchain;
2027 ret->current_rt.texture = target;
2028 ret->current_rt.sub_resource_idx = 0;
2029 ret->tid = GetCurrentThreadId();
2031 ret->render_offscreen = wined3d_resource_is_offscreen(&target->resource);
2032 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
2033 ret->valid = 1;
2035 ret->glCtx = ctx;
2036 ret->win_handle = swapchain->win_handle;
2037 ret->hdc = hdc;
2038 ret->hdc_is_private = hdc_is_private;
2039 ret->hdc_has_format = TRUE;
2040 ret->pixel_format = pixel_format;
2041 ret->needs_set = 1;
2043 /* Set up the context defaults */
2044 if (!context_set_current(ret))
2046 ERR("Cannot activate context to set up defaults.\n");
2047 device_context_remove(device, ret);
2048 context_release(ret);
2049 if (!wglDeleteContext(ctx))
2050 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
2051 goto out;
2054 if (context_debug_output_enabled(gl_info))
2056 GL_EXTCALL(glDebugMessageCallback(wined3d_debug_callback, ret));
2057 if (TRACE_ON(d3d_synchronous))
2058 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
2059 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
2060 if (ERR_ON(d3d))
2062 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR,
2063 GL_DONT_CARE, 0, NULL, GL_TRUE));
2065 if (FIXME_ON(d3d))
2067 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
2068 GL_DONT_CARE, 0, NULL, GL_TRUE));
2069 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
2070 GL_DONT_CARE, 0, NULL, GL_TRUE));
2071 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY,
2072 GL_DONT_CARE, 0, NULL, GL_TRUE));
2074 if (WARN_ON(d3d_perf))
2076 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE,
2077 GL_DONT_CARE, 0, NULL, GL_TRUE));
2081 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
2082 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
2084 TRACE("Setting up the screen\n");
2086 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
2088 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
2089 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
2091 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
2092 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
2094 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
2095 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
2097 else
2099 GLuint vao;
2101 GL_EXTCALL(glGenVertexArrays(1, &vao));
2102 GL_EXTCALL(glBindVertexArray(vao));
2103 checkGLcall("creating VAO");
2106 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
2107 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
2108 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
2109 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, 1);");
2111 if (gl_info->supported[ARB_VERTEX_BLEND])
2113 /* Direct3D always uses n-1 weights for n world matrices and uses
2114 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
2115 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
2116 * enabled as well. */
2117 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
2118 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
2120 if (gl_info->supported[NV_TEXTURE_SHADER2])
2122 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
2123 * the previous texture where to source the offset from is always unit - 1.
2125 for (i = 1; i < gl_info->limits.textures; ++i)
2127 context_active_texture(ret, gl_info, i);
2128 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
2129 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + i - 1);
2130 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
2133 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
2135 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
2136 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
2137 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
2138 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
2139 * is ever assigned.
2141 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
2142 * program and the dummy program is destroyed when the context is destroyed.
2144 static const char dummy_program[] =
2145 "!!ARBfp1.0\n"
2146 "MOV result.color, fragment.color.primary;\n"
2147 "END\n";
2148 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
2149 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
2150 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
2153 if (gl_info->supported[ARB_POINT_SPRITE])
2155 for (i = 0; i < gl_info->limits.textures; ++i)
2157 context_active_texture(ret, gl_info, i);
2158 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
2159 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
2163 if (gl_info->supported[ARB_PROVOKING_VERTEX])
2165 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
2167 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
2169 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
2171 if (!(d3d_info->wined3d_creation_flags & WINED3D_NO_PRIMITIVE_RESTART))
2173 if (gl_info->supported[ARB_ES3_COMPATIBILITY])
2175 gl_info->gl_ops.gl.p_glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
2176 checkGLcall("enable GL_PRIMITIVE_RESTART_FIXED_INDEX");
2178 else
2180 FIXME("OpenGL implementation does not support GL_PRIMITIVE_RESTART_FIXED_INDEX.\n");
2183 if (!(d3d_info->wined3d_creation_flags & WINED3D_LEGACY_CUBEMAP_FILTERING)
2184 && gl_info->supported[ARB_SEAMLESS_CUBE_MAP])
2186 gl_info->gl_ops.gl.p_glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
2187 checkGLcall("enable seamless cube map filtering");
2189 if (gl_info->supported[ARB_CLIP_CONTROL])
2190 GL_EXTCALL(glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT));
2191 device->shader_backend->shader_init_context_state(ret);
2192 ret->shader_update_mask = (1u << WINED3D_SHADER_TYPE_PIXEL)
2193 | (1u << WINED3D_SHADER_TYPE_VERTEX)
2194 | (1u << WINED3D_SHADER_TYPE_GEOMETRY)
2195 | (1u << WINED3D_SHADER_TYPE_HULL)
2196 | (1u << WINED3D_SHADER_TYPE_DOMAIN)
2197 | (1u << WINED3D_SHADER_TYPE_COMPUTE);
2199 /* If this happens to be the first context for the device, dummy textures
2200 * are not created yet. In that case, they will be created (and bound) by
2201 * create_dummy_textures right after this context is initialized. */
2202 if (device->dummy_textures.tex_2d)
2203 context_bind_dummy_textures(device, ret);
2205 TRACE("Created context %p.\n", ret);
2207 return ret;
2209 out:
2210 if (hdc) wined3d_release_dc(swapchain->win_handle, hdc);
2211 device->shader_backend->shader_free_context_data(ret);
2212 device->adapter->fragment_pipe->free_context_data(ret);
2213 HeapFree(GetProcessHeap(), 0, ret->texture_type);
2214 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
2215 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
2216 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
2217 HeapFree(GetProcessHeap(), 0, ret->fbo_key);
2218 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
2219 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
2220 HeapFree(GetProcessHeap(), 0, ret);
2221 return NULL;
2224 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
2226 BOOL destroy;
2228 TRACE("Destroying ctx %p\n", context);
2230 wined3d_from_cs(device->cs);
2232 /* We delay destroying a context when it is active. The context_release()
2233 * function invokes context_destroy() again while leaving the last level. */
2234 if (context->level)
2236 TRACE("Delaying destruction of context %p.\n", context);
2237 context->destroy_delayed = 1;
2238 /* FIXME: Get rid of a pointer to swapchain from wined3d_context. */
2239 context->swapchain = NULL;
2240 return;
2243 if (context->tid == GetCurrentThreadId() || !context->current)
2245 context_destroy_gl_resources(context);
2246 TlsSetValue(wined3d_context_tls_idx, NULL);
2247 destroy = TRUE;
2249 else
2251 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
2252 in wined3d_adapter may go away in the meantime */
2253 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
2254 *gl_info = *context->gl_info;
2255 context->gl_info = gl_info;
2256 context->destroyed = 1;
2257 destroy = FALSE;
2260 device->shader_backend->shader_free_context_data(context);
2261 device->adapter->fragment_pipe->free_context_data(context);
2262 HeapFree(GetProcessHeap(), 0, context->texture_type);
2263 HeapFree(GetProcessHeap(), 0, context->fbo_key);
2264 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
2265 HeapFree(GetProcessHeap(), 0, context->blit_targets);
2266 device_context_remove(device, context);
2267 if (destroy) HeapFree(GetProcessHeap(), 0, context);
2270 const DWORD *context_get_tex_unit_mapping(const struct wined3d_context *context,
2271 const struct wined3d_shader_version *shader_version, unsigned int *base, unsigned int *count)
2273 const struct wined3d_gl_info *gl_info = context->gl_info;
2275 if (!shader_version)
2277 *base = 0;
2278 *count = MAX_TEXTURES;
2279 return context->tex_unit_map;
2282 if (shader_version->major >= 4)
2284 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, shader_version->type, base, count);
2285 return NULL;
2288 switch (shader_version->type)
2290 case WINED3D_SHADER_TYPE_PIXEL:
2291 *base = 0;
2292 *count = MAX_FRAGMENT_SAMPLERS;
2293 break;
2294 case WINED3D_SHADER_TYPE_VERTEX:
2295 *base = MAX_FRAGMENT_SAMPLERS;
2296 *count = MAX_VERTEX_SAMPLERS;
2297 break;
2298 default:
2299 ERR("Unhandled shader type %#x.\n", shader_version->type);
2300 *base = 0;
2301 *count = 0;
2304 return context->tex_unit_map;
2307 /* Context activation is done by the caller. */
2308 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
2310 const GLdouble projection[] =
2312 2.0 / width, 0.0, 0.0, 0.0,
2313 0.0, 2.0 / height, 0.0, 0.0,
2314 0.0, 0.0, 2.0, 0.0,
2315 -1.0, -1.0, -1.0, 1.0,
2318 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
2319 checkGLcall("glMatrixMode(GL_PROJECTION)");
2320 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
2321 checkGLcall("glLoadMatrixd");
2322 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
2323 checkGLcall("glViewport");
2326 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
2328 const struct wined3d_texture *rt = context->current_rt.texture;
2329 unsigned int level;
2331 if (rt->swapchain)
2333 RECT window_size;
2335 GetClientRect(context->win_handle, &window_size);
2336 size->cx = window_size.right - window_size.left;
2337 size->cy = window_size.bottom - window_size.top;
2339 return;
2342 level = context->current_rt.sub_resource_idx % rt->level_count;
2343 size->cx = wined3d_texture_get_level_width(rt, level);
2344 size->cy = wined3d_texture_get_level_height(rt, level);
2347 /*****************************************************************************
2348 * SetupForBlit
2350 * Sets up a context for DirectDraw blitting.
2351 * All texture units are disabled, texture unit 0 is set as current unit
2352 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
2353 * color writing enabled for all channels
2354 * register combiners disabled, shaders disabled
2355 * world matrix is set to identity, texture matrix 0 too
2356 * projection matrix is setup for drawing screen coordinates
2358 * Params:
2359 * This: Device to activate the context for
2360 * context: Context to setup
2362 *****************************************************************************/
2363 /* Context activation is done by the caller. */
2364 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
2366 int i;
2367 const struct wined3d_gl_info *gl_info = context->gl_info;
2368 DWORD sampler;
2369 SIZE rt_size;
2371 TRACE("Setting up context %p for blitting\n", context);
2373 context_get_rt_size(context, &rt_size);
2375 if (context->last_was_blit)
2377 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
2379 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2380 context->blit_w = rt_size.cx;
2381 context->blit_h = rt_size.cy;
2382 /* No need to dirtify here, the states are still dirtified because
2383 * they weren't applied since the last SetupForBlit() call. */
2385 TRACE("Context is already set up for blitting, nothing to do\n");
2386 return;
2388 context->last_was_blit = TRUE;
2390 /* Disable all textures. The caller can then bind a texture it wants to blit
2391 * from
2393 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
2394 * function texture unit. No need to care for higher samplers
2396 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
2398 sampler = context->rev_tex_unit_map[i];
2399 context_active_texture(context, gl_info, i);
2401 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2403 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2404 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2406 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2407 checkGLcall("glDisable GL_TEXTURE_3D");
2408 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2410 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2411 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2413 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2414 checkGLcall("glDisable GL_TEXTURE_2D");
2416 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2417 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
2419 if (sampler != WINED3D_UNMAPPED_STAGE)
2421 if (sampler < MAX_TEXTURES)
2422 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2423 context_invalidate_state(context, STATE_SAMPLER(sampler));
2426 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
2427 GL_EXTCALL(glBindSampler(0, 0));
2428 context_active_texture(context, gl_info, 0);
2430 sampler = context->rev_tex_unit_map[0];
2432 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2434 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2435 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2437 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2438 checkGLcall("glDisable GL_TEXTURE_3D");
2439 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2441 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2442 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2444 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2445 checkGLcall("glDisable GL_TEXTURE_2D");
2447 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2449 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
2450 checkGLcall("glMatrixMode(GL_TEXTURE)");
2451 gl_info->gl_ops.gl.p_glLoadIdentity();
2452 checkGLcall("glLoadIdentity()");
2454 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2456 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
2457 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
2458 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
2461 if (sampler != WINED3D_UNMAPPED_STAGE)
2463 if (sampler < MAX_TEXTURES)
2465 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
2466 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2468 context_invalidate_state(context, STATE_SAMPLER(sampler));
2471 /* Other misc states */
2472 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2473 checkGLcall("glDisable(GL_ALPHA_TEST)");
2474 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2475 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2476 checkGLcall("glDisable GL_LIGHTING");
2477 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2478 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2479 checkGLcall("glDisable GL_DEPTH_TEST");
2480 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2481 glDisableWINE(GL_FOG);
2482 checkGLcall("glDisable GL_FOG");
2483 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
2484 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2485 checkGLcall("glDisable GL_BLEND");
2486 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2487 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2488 checkGLcall("glDisable GL_CULL_FACE");
2489 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2490 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2491 checkGLcall("glDisable GL_STENCIL_TEST");
2492 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2493 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2494 checkGLcall("glDisable GL_SCISSOR_TEST");
2495 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2496 if (gl_info->supported[ARB_POINT_SPRITE])
2498 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2499 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2500 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2502 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2503 checkGLcall("glColorMask");
2504 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2505 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2506 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2507 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2508 if (gl_info->supported[EXT_SECONDARY_COLOR])
2510 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2511 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2512 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2515 /* Setup transforms */
2516 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2517 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2518 gl_info->gl_ops.gl.p_glLoadIdentity();
2519 checkGLcall("glLoadIdentity()");
2520 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2522 context->last_was_rhw = TRUE;
2523 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2525 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2526 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2527 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2528 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2529 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2530 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2531 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2533 /* FIXME: Make draw_textured_quad() able to work with a upper left origin. */
2534 if (gl_info->supported[ARB_CLIP_CONTROL])
2535 GL_EXTCALL(glClipControl(GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE));
2537 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2539 /* Disable shaders */
2540 device->shader_backend->shader_disable(device->shader_priv, context);
2542 context->blit_w = rt_size.cx;
2543 context->blit_h = rt_size.cy;
2544 context_invalidate_state(context, STATE_VIEWPORT);
2545 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2548 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2550 return rt_mask & (1u << 31);
2553 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2555 return rt_mask & ~(1u << 31);
2558 /* Context activation is done by the caller. */
2559 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2561 const struct wined3d_gl_info *gl_info = context->gl_info;
2563 if (!rt_mask)
2565 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2566 checkGLcall("glDrawBuffer()");
2568 else if (is_rt_mask_onscreen(rt_mask))
2570 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2571 checkGLcall("glDrawBuffer()");
2573 else
2575 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2577 unsigned int i = 0;
2579 while (rt_mask)
2581 if (rt_mask & 1)
2582 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2583 else
2584 context->draw_buffers[i] = GL_NONE;
2586 rt_mask >>= 1;
2587 ++i;
2590 if (gl_info->supported[ARB_DRAW_BUFFERS])
2592 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2593 checkGLcall("glDrawBuffers()");
2595 else
2597 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2598 checkGLcall("glDrawBuffer()");
2601 else
2603 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2608 /* Context activation is done by the caller. */
2609 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2611 const struct wined3d_gl_info *gl_info = context->gl_info;
2612 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2613 DWORD new_mask = context_generate_rt_mask(buffer);
2615 if (new_mask == *current_mask)
2616 return;
2618 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2619 checkGLcall("glDrawBuffer()");
2621 *current_mask = new_mask;
2624 /* Context activation is done by the caller. */
2625 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2627 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2628 checkGLcall("glActiveTexture");
2629 context->active_texture = unit;
2632 void context_bind_bo(struct wined3d_context *context, GLenum binding, GLuint name)
2634 const struct wined3d_gl_info *gl_info = context->gl_info;
2636 if (binding == GL_ELEMENT_ARRAY_BUFFER)
2637 context_invalidate_state(context, STATE_INDEXBUFFER);
2639 GL_EXTCALL(glBindBuffer(binding, name));
2642 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2644 const struct wined3d_gl_info *gl_info = context->gl_info;
2645 DWORD unit = context->active_texture;
2646 DWORD old_texture_type = context->texture_type[unit];
2648 if (name)
2650 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2651 checkGLcall("glBindTexture");
2653 else
2655 target = GL_NONE;
2658 if (old_texture_type != target)
2660 const struct wined3d_device *device = context->device;
2662 switch (old_texture_type)
2664 case GL_NONE:
2665 /* nothing to do */
2666 break;
2667 case GL_TEXTURE_2D:
2668 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_textures.tex_2d);
2669 checkGLcall("glBindTexture");
2670 break;
2671 case GL_TEXTURE_2D_ARRAY:
2672 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, device->dummy_textures.tex_2d_array);
2673 checkGLcall("glBindTexture");
2674 break;
2675 case GL_TEXTURE_RECTANGLE_ARB:
2676 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_textures.tex_rect);
2677 checkGLcall("glBindTexture");
2678 break;
2679 case GL_TEXTURE_CUBE_MAP:
2680 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_textures.tex_cube);
2681 checkGLcall("glBindTexture");
2682 break;
2683 case GL_TEXTURE_CUBE_MAP_ARRAY:
2684 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, device->dummy_textures.tex_cube_array);
2685 checkGLcall("glBindTexture");
2686 break;
2687 case GL_TEXTURE_3D:
2688 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_textures.tex_3d);
2689 checkGLcall("glBindTexture");
2690 break;
2691 case GL_TEXTURE_BUFFER:
2692 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_BUFFER, device->dummy_textures.tex_buffer);
2693 checkGLcall("glBindTexture");
2694 break;
2695 default:
2696 ERR("Unexpected texture target %#x.\n", old_texture_type);
2699 context->texture_type[unit] = target;
2703 void *context_map_bo_address(struct wined3d_context *context,
2704 const struct wined3d_bo_address *data, size_t size, GLenum binding, DWORD flags)
2706 const struct wined3d_gl_info *gl_info;
2707 BYTE *memory;
2709 if (!data->buffer_object)
2710 return data->addr;
2712 gl_info = context->gl_info;
2713 context_bind_bo(context, binding, data->buffer_object);
2715 if (gl_info->supported[ARB_MAP_BUFFER_RANGE])
2717 GLbitfield map_flags = wined3d_resource_gl_map_flags(flags) & ~GL_MAP_FLUSH_EXPLICIT_BIT;
2718 memory = GL_EXTCALL(glMapBufferRange(binding, (INT_PTR)data->addr, size, map_flags));
2720 else
2722 memory = GL_EXTCALL(glMapBuffer(binding, wined3d_resource_gl_legacy_map_flags(flags)));
2723 memory += (INT_PTR)data->addr;
2726 context_bind_bo(context, binding, 0);
2727 checkGLcall("Map buffer object");
2729 return memory;
2732 void context_unmap_bo_address(struct wined3d_context *context,
2733 const struct wined3d_bo_address *data, GLenum binding)
2735 const struct wined3d_gl_info *gl_info;
2737 if (!data->buffer_object)
2738 return;
2740 gl_info = context->gl_info;
2741 context_bind_bo(context, binding, data->buffer_object);
2742 GL_EXTCALL(glUnmapBuffer(binding));
2743 context_bind_bo(context, binding, 0);
2744 checkGLcall("Unmap buffer object");
2747 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2749 if (context->render_offscreen == offscreen)
2750 return;
2752 context_invalidate_state(context, STATE_VIEWPORT);
2753 context_invalidate_state(context, STATE_SCISSORRECT);
2754 if (!context->gl_info->supported[ARB_CLIP_CONTROL])
2756 context_invalidate_state(context, STATE_FRONTFACE);
2757 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2758 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2760 context_invalidate_state(context, STATE_SHADER(WINED3D_SHADER_TYPE_DOMAIN));
2761 if (context->gl_info->supported[ARB_FRAGMENT_COORD_CONVENTIONS])
2762 context_invalidate_state(context, STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL));
2763 context->render_offscreen = offscreen;
2766 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2767 const struct wined3d_format *required)
2769 if (existing == required)
2770 return TRUE;
2771 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2772 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2773 return FALSE;
2774 if (existing->depth_size < required->depth_size)
2775 return FALSE;
2776 /* If stencil bits are used the exact amount is required - otherwise
2777 * wrapping won't work correctly. */
2778 if (required->stencil_size && required->stencil_size != existing->stencil_size)
2779 return FALSE;
2780 return TRUE;
2783 /* Context activation is done by the caller. */
2784 static void context_validate_onscreen_formats(struct wined3d_context *context,
2785 const struct wined3d_rendertarget_view *depth_stencil)
2787 /* Onscreen surfaces are always in a swapchain */
2788 struct wined3d_swapchain *swapchain = context->current_rt.texture->swapchain;
2790 if (context->render_offscreen || !depth_stencil) return;
2791 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2793 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2794 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2795 * format. */
2796 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2798 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2799 if (!(wined3d_texture_load_location(context->current_rt.texture, context->current_rt.sub_resource_idx,
2800 context, WINED3D_LOCATION_TEXTURE_RGB)))
2801 ERR("Failed to load location.\n");
2802 swapchain->render_to_fbo = TRUE;
2803 swapchain_update_draw_bindings(swapchain);
2804 context_set_render_offscreen(context, TRUE);
2807 GLenum context_get_offscreen_gl_buffer(const struct wined3d_context *context)
2809 switch (wined3d_settings.offscreen_rendering_mode)
2811 case ORM_FBO:
2812 return GL_COLOR_ATTACHMENT0;
2814 case ORM_BACKBUFFER:
2815 return context->aux_buffers > 0 ? GL_AUX0 : GL_BACK;
2817 default:
2818 FIXME("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
2819 return GL_BACK;
2823 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_context *context, struct wined3d_texture *rt)
2825 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2826 return 0;
2827 else if (rt->swapchain)
2828 return context_generate_rt_mask_from_resource(&rt->resource);
2829 else
2830 return context_generate_rt_mask(context_get_offscreen_gl_buffer(context));
2833 /* Context activation is done by the caller. */
2834 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2836 struct wined3d_texture *rt = context->current_rt.texture;
2837 struct wined3d_surface *surface;
2838 DWORD rt_mask, *cur_mask;
2840 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2842 context_validate_onscreen_formats(context, NULL);
2844 if (context->render_offscreen)
2846 wined3d_texture_load(rt, context, FALSE);
2848 surface = rt->sub_resources[context->current_rt.sub_resource_idx].u.surface;
2849 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, surface, NULL, rt->resource.draw_binding);
2850 if (rt->resource.format->id != WINED3DFMT_NULL)
2851 rt_mask = 1;
2852 else
2853 rt_mask = 0;
2855 else
2857 context->current_fbo = NULL;
2858 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2859 rt_mask = context_generate_rt_mask_from_resource(&rt->resource);
2862 else
2864 rt_mask = context_generate_rt_mask_no_fbo(context, rt);
2867 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2869 if (rt_mask != *cur_mask)
2871 context_apply_draw_buffers(context, rt_mask);
2872 *cur_mask = rt_mask;
2875 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2877 context_check_fbo_status(context, GL_FRAMEBUFFER);
2880 SetupForBlit(device, context);
2881 context_invalidate_state(context, STATE_FRAMEBUFFER);
2884 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2885 const struct wined3d_rendertarget_view *ds)
2887 unsigned int i;
2889 if (ds) return TRUE;
2891 for (i = 0; i < rt_count; ++i)
2893 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2894 return TRUE;
2897 WARN("Invalid render target config, need at least one attachment.\n");
2898 return FALSE;
2901 /* Context activation is done by the caller. */
2902 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_state *state,
2903 UINT rt_count, const struct wined3d_fb_state *fb)
2905 struct wined3d_rendertarget_view **rts = fb->render_targets;
2906 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2907 const struct wined3d_gl_info *gl_info = context->gl_info;
2908 DWORD rt_mask = 0, *cur_mask;
2909 unsigned int i;
2911 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != state->fb
2912 || rt_count != gl_info->limits.buffers)
2914 if (!context_validate_rt_config(rt_count, rts, dsv))
2915 return FALSE;
2917 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2919 context_validate_onscreen_formats(context, dsv);
2921 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2923 memset(context->blit_targets, 0, gl_info->limits.buffers * sizeof(*context->blit_targets));
2924 for (i = 0; i < rt_count; ++i)
2926 if (rts[i])
2928 context->blit_targets[i].gl_view = rts[i]->gl_view;
2929 context->blit_targets[i].resource = rts[i]->resource;
2930 context->blit_targets[i].sub_resource_idx = rts[i]->sub_resource_idx;
2931 context->blit_targets[i].layer_count = rts[i]->layer_count;
2933 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2934 rt_mask |= (1u << i);
2936 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2937 wined3d_rendertarget_view_get_surface(dsv),
2938 rt_count ? rts[0]->resource->draw_binding : 0,
2939 dsv ? dsv->resource->draw_binding : 0);
2941 else
2943 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2944 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2945 rt_mask = context_generate_rt_mask_from_resource(rts[0]->resource);
2948 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2949 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2950 * state management allows this */
2951 context_invalidate_state(context, STATE_FRAMEBUFFER);
2953 else
2955 rt_mask = context_generate_rt_mask_no_fbo(context,
2956 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
2959 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2960 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
2962 for (i = 0; i < rt_count; ++i)
2964 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2965 rt_mask |= (1u << i);
2968 else
2970 rt_mask = context_generate_rt_mask_no_fbo(context,
2971 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
2974 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2976 if (rt_mask != *cur_mask)
2978 context_apply_draw_buffers(context, rt_mask);
2979 *cur_mask = rt_mask;
2980 context_invalidate_state(context, STATE_FRAMEBUFFER);
2983 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2985 context_check_fbo_status(context, GL_FRAMEBUFFER);
2988 context->last_was_blit = FALSE;
2990 /* Blending and clearing should be orthogonal, but tests on the nvidia
2991 * driver show that disabling blending when clearing improves the clearing
2992 * performance incredibly. */
2993 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2994 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2995 if (rt_count && gl_info->supported[ARB_FRAMEBUFFER_SRGB])
2997 if (needs_srgb_write(context, state, fb))
2998 gl_info->gl_ops.gl.p_glEnable(GL_FRAMEBUFFER_SRGB);
2999 else
3000 gl_info->gl_ops.gl.p_glDisable(GL_FRAMEBUFFER_SRGB);
3001 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3003 checkGLcall("setting up state for clear");
3005 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3006 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
3007 context_invalidate_state(context, STATE_SCISSORRECT);
3009 return TRUE;
3012 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_state *state)
3014 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
3015 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
3016 DWORD rt_mask, rt_mask_bits;
3017 unsigned int i;
3019 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
3020 return context_generate_rt_mask_no_fbo(context, wined3d_rendertarget_view_get_surface(rts[0])->container);
3021 else if (!context->render_offscreen)
3022 return context_generate_rt_mask_from_resource(rts[0]->resource);
3024 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
3025 rt_mask &= context->d3d_info->valid_rt_mask;
3026 rt_mask_bits = rt_mask;
3027 i = 0;
3028 while (rt_mask_bits)
3030 rt_mask_bits &= ~(1u << i);
3031 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
3032 rt_mask &= ~(1u << i);
3034 i++;
3037 return rt_mask;
3040 /* Context activation is done by the caller. */
3041 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
3043 DWORD rt_mask = find_draw_buffers_mask(context, state);
3044 const struct wined3d_fb_state *fb = state->fb;
3045 DWORD *cur_mask;
3047 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3049 if (!context->render_offscreen)
3051 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
3052 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
3054 else
3056 unsigned int i;
3058 memset(context->blit_targets, 0, context->gl_info->limits.buffers * sizeof (*context->blit_targets));
3059 for (i = 0; i < context->gl_info->limits.buffers; ++i)
3061 if (fb->render_targets[i])
3063 context->blit_targets[i].gl_view = fb->render_targets[i]->gl_view;
3064 context->blit_targets[i].resource = fb->render_targets[i]->resource;
3065 context->blit_targets[i].sub_resource_idx = fb->render_targets[i]->sub_resource_idx;
3066 context->blit_targets[i].layer_count = fb->render_targets[i]->layer_count;
3069 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
3070 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
3071 fb->render_targets[0] ? fb->render_targets[0]->resource->draw_binding : 0,
3072 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
3076 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3077 if (rt_mask != *cur_mask)
3079 context_apply_draw_buffers(context, rt_mask);
3080 *cur_mask = rt_mask;
3082 context->constant_update_mask |= WINED3D_SHADER_CONST_PS_Y_CORR;
3085 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
3087 DWORD i = context->rev_tex_unit_map[unit];
3088 DWORD j = context->tex_unit_map[stage];
3090 TRACE("Mapping stage %u to unit %u.\n", stage, unit);
3091 context->tex_unit_map[stage] = unit;
3092 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
3093 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
3095 context->rev_tex_unit_map[unit] = stage;
3096 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
3097 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
3100 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
3102 DWORD i;
3104 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
3105 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
3108 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
3109 const struct wined3d_state *state)
3111 UINT i, start, end;
3113 context->fixed_function_usage_map = 0;
3114 for (i = 0; i < MAX_TEXTURES; ++i)
3116 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
3117 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
3118 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
3119 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
3120 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
3121 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
3122 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
3123 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
3125 /* Not used, and disable higher stages. */
3126 if (color_op == WINED3D_TOP_DISABLE)
3127 break;
3129 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
3130 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
3131 || ((color_arg3 == WINED3DTA_TEXTURE)
3132 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
3133 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
3134 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
3135 || ((alpha_arg3 == WINED3DTA_TEXTURE)
3136 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
3137 context->fixed_function_usage_map |= (1u << i);
3139 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
3140 && i < MAX_TEXTURES - 1)
3141 context->fixed_function_usage_map |= (1u << (i + 1));
3144 if (i < context->lowest_disabled_stage)
3146 start = i;
3147 end = context->lowest_disabled_stage;
3149 else
3151 start = context->lowest_disabled_stage;
3152 end = i;
3155 context->lowest_disabled_stage = i;
3156 for (i = start + 1; i < end; ++i)
3158 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3162 static void context_map_fixed_function_samplers(struct wined3d_context *context,
3163 const struct wined3d_state *state)
3165 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3166 unsigned int i, tex;
3167 WORD ffu_map;
3169 ffu_map = context->fixed_function_usage_map;
3171 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
3172 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
3174 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3176 if (!(ffu_map & 1))
3177 continue;
3179 if (context->tex_unit_map[i] != i)
3181 context_map_stage(context, i, i);
3182 context_invalidate_state(context, STATE_SAMPLER(i));
3183 context_invalidate_texture_stage(context, i);
3186 return;
3189 /* Now work out the mapping */
3190 tex = 0;
3191 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3193 if (!(ffu_map & 1))
3194 continue;
3196 if (context->tex_unit_map[i] != tex)
3198 context_map_stage(context, i, tex);
3199 context_invalidate_state(context, STATE_SAMPLER(i));
3200 context_invalidate_texture_stage(context, i);
3203 ++tex;
3207 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
3209 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3210 const struct wined3d_shader_resource_info *resource_info =
3211 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
3212 unsigned int i;
3214 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3216 if (resource_info[i].type && context->tex_unit_map[i] != i)
3218 context_map_stage(context, i, i);
3219 context_invalidate_state(context, STATE_SAMPLER(i));
3220 if (i < d3d_info->limits.ffp_blend_stages)
3221 context_invalidate_texture_stage(context, i);
3226 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
3227 const struct wined3d_shader_resource_info *ps_resource_info, DWORD unit)
3229 DWORD current_mapping = context->rev_tex_unit_map[unit];
3231 /* Not currently used */
3232 if (current_mapping == WINED3D_UNMAPPED_STAGE)
3233 return TRUE;
3235 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
3237 /* Used by a fragment sampler */
3239 if (!ps_resource_info)
3241 /* No pixel shader, check fixed function */
3242 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1u << current_mapping));
3245 /* Pixel shader, check the shader's sampler map */
3246 return !ps_resource_info[current_mapping].type;
3249 return TRUE;
3252 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
3254 const struct wined3d_shader_resource_info *vs_resource_info =
3255 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
3256 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
3257 const struct wined3d_gl_info *gl_info = context->gl_info;
3258 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.graphics_samplers) - 1;
3259 int i;
3261 /* Note that we only care if a resource is used or not, not the
3262 * resource's specific type. Otherwise we'd need to call
3263 * shader_update_samplers() here for 1.x pixelshaders. */
3264 if (ps)
3265 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
3267 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3269 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
3270 if (vs_resource_info[i].type)
3272 while (start >= 0)
3274 if (context_unit_free_for_vs(context, ps_resource_info, start))
3276 if (context->tex_unit_map[vsampler_idx] != start)
3278 context_map_stage(context, vsampler_idx, start);
3279 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
3282 --start;
3283 break;
3286 --start;
3288 if (context->tex_unit_map[vsampler_idx] == WINED3D_UNMAPPED_STAGE)
3289 WARN("Couldn't find a free texture unit for vertex sampler %u.\n", i);
3294 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
3296 const struct wined3d_gl_info *gl_info = context->gl_info;
3297 BOOL vs = use_vs(state);
3298 BOOL ps = use_ps(state);
3300 if (!ps)
3301 context_update_fixed_function_usage_map(context, state);
3303 /* Try to go for a 1:1 mapping of the samplers when possible. Pixel shaders
3304 * need a 1:1 map at the moment.
3305 * When the mapping of a stage is changed, sampler and ALL texture stage
3306 * states have to be reset. */
3308 if (gl_info->limits.graphics_samplers >= MAX_COMBINED_SAMPLERS)
3309 return;
3311 if (ps)
3312 context_map_psamplers(context, state);
3313 else
3314 context_map_fixed_function_samplers(context, state);
3316 if (vs)
3317 context_map_vsamplers(context, ps, state);
3320 /* Context activation is done by the caller. */
3321 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
3323 DWORD rt_mask, *cur_mask;
3325 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
3327 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3328 rt_mask = find_draw_buffers_mask(context, state);
3329 if (rt_mask != *cur_mask)
3331 context_apply_draw_buffers(context, rt_mask);
3332 *cur_mask = rt_mask;
3336 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
3338 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
3339 *regnum = WINED3D_FFP_POSITION;
3340 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
3341 *regnum = WINED3D_FFP_BLENDWEIGHT;
3342 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
3343 *regnum = WINED3D_FFP_BLENDINDICES;
3344 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
3345 *regnum = WINED3D_FFP_NORMAL;
3346 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
3347 *regnum = WINED3D_FFP_PSIZE;
3348 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
3349 *regnum = WINED3D_FFP_DIFFUSE;
3350 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
3351 *regnum = WINED3D_FFP_SPECULAR;
3352 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
3353 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
3354 else
3356 WARN("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
3357 *regnum = ~0u;
3358 return FALSE;
3361 return TRUE;
3364 /* Context activation is done by the caller. */
3365 void wined3d_stream_info_from_declaration(struct wined3d_stream_info *stream_info,
3366 const struct wined3d_state *state, const struct wined3d_gl_info *gl_info,
3367 const struct wined3d_d3d_info *d3d_info)
3369 /* We need to deal with frequency data! */
3370 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
3371 BOOL generic_attributes = d3d_info->ffp_generic_attributes;
3372 BOOL use_vshader = use_vs(state);
3373 unsigned int i;
3375 stream_info->use_map = 0;
3376 stream_info->swizzle_map = 0;
3377 stream_info->position_transformed = 0;
3379 if (!declaration)
3380 return;
3382 stream_info->position_transformed = declaration->position_transformed;
3384 /* Translate the declaration into strided data. */
3385 for (i = 0; i < declaration->element_count; ++i)
3387 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
3388 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
3389 BOOL stride_used;
3390 unsigned int idx;
3392 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
3393 element, i + 1, declaration->element_count);
3395 if (!stream->buffer)
3396 continue;
3398 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
3400 if (use_vshader)
3402 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
3404 stride_used = FALSE;
3406 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
3408 /* TODO: Assuming vertexdeclarations are usually used with the
3409 * same or a similar shader, it might be worth it to store the
3410 * last used output slot and try that one first. */
3411 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
3412 element->usage, element->usage_idx, &idx);
3414 else
3416 idx = element->output_slot;
3417 stride_used = TRUE;
3420 else
3422 if (!generic_attributes && !element->ffp_valid)
3424 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
3425 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
3426 stride_used = FALSE;
3428 else
3430 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
3434 if (stride_used)
3436 TRACE("Load %s array %u [usage %s, usage_idx %u, "
3437 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
3438 use_vshader ? "shader": "fixed function", idx,
3439 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
3440 element->offset, stream->stride, debug_d3dformat(element->format->id),
3441 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
3443 stream_info->elements[idx].format = element->format;
3444 stream_info->elements[idx].data.buffer_object = 0;
3445 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
3446 stream_info->elements[idx].stride = stream->stride;
3447 stream_info->elements[idx].stream_idx = element->input_slot;
3448 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
3450 stream_info->elements[idx].divisor = 1;
3452 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
3454 stream_info->elements[idx].divisor = element->instance_data_step_rate;
3455 if (!element->instance_data_step_rate)
3456 FIXME("Instance step rate 0 not implemented.\n");
3458 else
3460 stream_info->elements[idx].divisor = 0;
3463 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3464 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
3466 stream_info->swizzle_map |= 1u << idx;
3468 stream_info->use_map |= 1u << idx;
3473 /* Context activation is done by the caller. */
3474 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
3476 struct wined3d_stream_info *stream_info = &context->stream_info;
3477 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3478 const struct wined3d_gl_info *gl_info = context->gl_info;
3479 DWORD prev_all_vbo = stream_info->all_vbo;
3480 unsigned int i;
3481 WORD map;
3483 wined3d_stream_info_from_declaration(stream_info, state, gl_info, d3d_info);
3485 stream_info->all_vbo = 1;
3486 context->num_buffer_queries = 0;
3487 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
3489 struct wined3d_stream_info_element *element;
3490 struct wined3d_bo_address data;
3491 struct wined3d_buffer *buffer;
3493 if (!(map & 1))
3494 continue;
3496 element = &stream_info->elements[i];
3497 buffer = state->streams[element->stream_idx].buffer;
3499 /* We can't use VBOs if the base vertex index is negative. OpenGL
3500 * doesn't accept negative offsets (or rather offsets bigger than the
3501 * VBO, because the pointer is unsigned), so use system memory
3502 * sources. In most sane cases the pointer - offset will still be > 0,
3503 * otherwise it will wrap around to some big value. Hope that with the
3504 * indices the driver wraps it back internally. If not,
3505 * draw_primitive_immediate_mode() is needed, including a vertex buffer
3506 * path. */
3507 if (state->load_base_vertex_index < 0)
3509 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
3510 state->load_base_vertex_index);
3511 element->data.buffer_object = 0;
3512 element->data.addr += (ULONG_PTR)wined3d_buffer_load_sysmem(buffer, context);
3513 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
3514 FIXME("System memory vertex data load offset is negative!\n");
3516 else
3518 wined3d_buffer_load(buffer, context, state);
3519 wined3d_buffer_get_memory(buffer, &data, buffer->locations);
3520 element->data.buffer_object = data.buffer_object;
3521 element->data.addr += (ULONG_PTR)data.addr;
3524 if (!element->data.buffer_object)
3525 stream_info->all_vbo = 0;
3527 if (buffer->query)
3528 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
3530 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
3533 if (prev_all_vbo != stream_info->all_vbo)
3534 context_invalidate_state(context, STATE_INDEXBUFFER);
3536 context->use_immediate_mode_draw = FALSE;
3538 if (stream_info->all_vbo)
3539 return;
3541 if (use_vs(state))
3543 if (state->vertex_declaration->half_float_conv_needed)
3545 TRACE("Using immediate mode draw with vertex shaders for FLOAT16 conversion.\n");
3546 context->use_immediate_mode_draw = TRUE;
3549 else
3551 WORD slow_mask = -!d3d_info->ffp_generic_attributes & (1u << WINED3D_FFP_PSIZE);
3552 slow_mask |= -(!gl_info->supported[ARB_VERTEX_ARRAY_BGRA] && !d3d_info->ffp_generic_attributes)
3553 & ((1u << WINED3D_FFP_DIFFUSE) | (1u << WINED3D_FFP_SPECULAR) | (1u << WINED3D_FFP_BLENDWEIGHT));
3555 if ((stream_info->position_transformed && !d3d_info->xyzrhw)
3556 || (stream_info->use_map & slow_mask))
3557 context->use_immediate_mode_draw = TRUE;
3561 /* Context activation is done by the caller. */
3562 static void context_preload_texture(struct wined3d_context *context,
3563 const struct wined3d_state *state, unsigned int idx)
3565 struct wined3d_texture *texture;
3567 if (!(texture = state->textures[idx]))
3568 return;
3570 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3573 /* Context activation is done by the caller. */
3574 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3576 unsigned int i;
3578 if (use_vs(state))
3580 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3582 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3583 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3587 if (use_ps(state))
3589 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3591 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3592 context_preload_texture(context, state, i);
3595 else
3597 WORD ffu_map = context->fixed_function_usage_map;
3599 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3601 if (ffu_map & 1)
3602 context_preload_texture(context, state, i);
3607 static void context_load_shader_resources(struct wined3d_context *context, const struct wined3d_state *state,
3608 unsigned int shader_mask)
3610 struct wined3d_shader_sampler_map_entry *entry;
3611 struct wined3d_shader_resource_view *view;
3612 struct wined3d_shader *shader;
3613 unsigned int i, j;
3615 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3617 if (!(shader_mask & (1u << i)))
3618 continue;
3620 if (!(shader = state->shader[i]))
3621 continue;
3623 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3625 if (state->cb[i][j])
3626 wined3d_buffer_load(state->cb[i][j], context, state);
3629 for (j = 0; j < shader->reg_maps.sampler_map.count; ++j)
3631 entry = &shader->reg_maps.sampler_map.entries[j];
3633 if (!(view = state->shader_resource_view[i][entry->resource_idx]))
3634 continue;
3636 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3637 wined3d_buffer_load(buffer_from_resource(view->resource), context, state);
3638 else
3639 wined3d_texture_load(texture_from_resource(view->resource), context, FALSE);
3644 static void context_bind_shader_resources(struct wined3d_context *context,
3645 const struct wined3d_state *state, enum wined3d_shader_type shader_type)
3647 unsigned int bind_idx, shader_sampler_count, base, count, i;
3648 const struct wined3d_device *device = context->device;
3649 struct wined3d_shader_sampler_map_entry *entry;
3650 struct wined3d_shader_resource_view *view;
3651 const struct wined3d_shader *shader;
3652 struct wined3d_sampler *sampler;
3653 const DWORD *tex_unit_map;
3655 if (!(shader = state->shader[shader_type]))
3656 return;
3658 tex_unit_map = context_get_tex_unit_mapping(context,
3659 &shader->reg_maps.shader_version, &base, &count);
3661 shader_sampler_count = shader->reg_maps.sampler_map.count;
3662 if (shader_sampler_count > count)
3663 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3664 shader, shader_sampler_count, count);
3665 count = min(shader_sampler_count, count);
3667 for (i = 0; i < count; ++i)
3669 entry = &shader->reg_maps.sampler_map.entries[i];
3670 bind_idx = base + entry->bind_idx;
3671 if (tex_unit_map)
3672 bind_idx = tex_unit_map[bind_idx];
3674 if (!(view = state->shader_resource_view[shader_type][entry->resource_idx]))
3676 WARN("No resource view bound at index %u, %u.\n", shader_type, entry->resource_idx);
3677 continue;
3680 if (entry->sampler_idx == WINED3D_SAMPLER_DEFAULT)
3681 sampler = device->default_sampler;
3682 else if (!(sampler = state->sampler[shader_type][entry->sampler_idx]))
3683 sampler = device->null_sampler;
3684 wined3d_shader_resource_view_bind(view, bind_idx, sampler, context);
3688 static void context_load_unordered_access_resources(struct wined3d_context *context,
3689 const struct wined3d_shader *shader, struct wined3d_unordered_access_view * const *views)
3691 struct wined3d_unordered_access_view *view;
3692 struct wined3d_texture *texture;
3693 struct wined3d_buffer *buffer;
3694 unsigned int i;
3696 context->uses_uavs = 0;
3698 if (!shader)
3699 return;
3701 for (i = 0; i < MAX_UNORDERED_ACCESS_VIEWS; ++i)
3703 if (!(view = views[i]))
3704 continue;
3706 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3708 buffer = buffer_from_resource(view->resource);
3709 wined3d_buffer_load_location(buffer, context, WINED3D_LOCATION_BUFFER);
3710 wined3d_unordered_access_view_invalidate_location(view, ~WINED3D_LOCATION_BUFFER);
3712 else
3714 texture = texture_from_resource(view->resource);
3715 wined3d_texture_load(texture, context, FALSE);
3716 wined3d_unordered_access_view_invalidate_location(view, ~WINED3D_LOCATION_TEXTURE_RGB);
3719 context->uses_uavs = 1;
3723 static void context_bind_unordered_access_views(struct wined3d_context *context,
3724 const struct wined3d_shader *shader, struct wined3d_unordered_access_view * const *views)
3726 const struct wined3d_gl_info *gl_info = context->gl_info;
3727 struct wined3d_unordered_access_view *view;
3728 GLuint texture_name;
3729 unsigned int i;
3730 GLint level;
3732 if (!shader)
3733 return;
3735 for (i = 0; i < MAX_UNORDERED_ACCESS_VIEWS; ++i)
3737 if (!(view = views[i]))
3739 if (shader->reg_maps.uav_resource_info[i].type)
3740 WARN("No unordered access view bound at index %u.\n", i);
3741 GL_EXTCALL(glBindImageTexture(i, 0, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8));
3742 continue;
3745 if (view->gl_view.name)
3747 texture_name = view->gl_view.name;
3748 level = 0;
3750 else if (view->resource->type != WINED3D_RTYPE_BUFFER)
3752 struct wined3d_texture *texture = texture_from_resource(view->resource);
3753 texture_name = wined3d_texture_get_texture_name(texture, context, FALSE);
3754 level = view->desc.u.texture.level_idx;
3756 else
3758 FIXME("Unsupported buffer unordered access view.\n");
3759 GL_EXTCALL(glBindImageTexture(i, 0, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8));
3760 continue;
3763 GL_EXTCALL(glBindImageTexture(i, texture_name, level, GL_TRUE, 0, GL_READ_WRITE,
3764 view->format->glInternal));
3766 if (view->counter_bo)
3767 GL_EXTCALL(glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, i, view->counter_bo));
3769 checkGLcall("Bind unordered access views");
3772 static void context_load_stream_output_buffers(struct wined3d_context *context,
3773 const struct wined3d_state *state)
3775 unsigned int i;
3777 for (i = 0; i < ARRAY_SIZE(state->stream_output); ++i)
3779 struct wined3d_buffer *buffer;
3780 if (!(buffer = state->stream_output[i].buffer))
3781 continue;
3783 wined3d_buffer_load(buffer, context, state);
3784 wined3d_buffer_invalidate_location(buffer, ~WINED3D_LOCATION_BUFFER);
3788 /* Context activation is done by the caller. */
3789 BOOL context_apply_draw_state(struct wined3d_context *context,
3790 const struct wined3d_device *device, const struct wined3d_state *state)
3792 const struct StateEntry *state_table = context->state_table;
3793 const struct wined3d_gl_info *gl_info = context->gl_info;
3794 const struct wined3d_fb_state *fb = state->fb;
3795 unsigned int i;
3796 WORD map;
3798 if (!context_validate_rt_config(gl_info->limits.buffers, fb->render_targets, fb->depth_stencil))
3799 return FALSE;
3801 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3803 context_validate_onscreen_formats(context, fb->depth_stencil);
3806 /* Preload resources before FBO setup. Texture preload in particular may
3807 * result in changes to the current FBO, due to using e.g. FBO blits for
3808 * updating a resource location. */
3809 context_update_tex_unit_map(context, state);
3810 context_preload_textures(context, state);
3811 context_load_shader_resources(context, state, ~(1u << WINED3D_SHADER_TYPE_COMPUTE));
3812 context_load_unordered_access_resources(context, state->shader[WINED3D_SHADER_TYPE_PIXEL],
3813 state->unordered_access_view[WINED3D_PIPELINE_GRAPHICS]);
3814 context_load_stream_output_buffers(context, state);
3815 /* TODO: Right now the dependency on the vertex shader is necessary
3816 * since wined3d_stream_info_from_declaration() depends on the reg_maps of
3817 * the current VS but maybe it's possible to relax the coupling in some
3818 * situations at least. */
3819 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3820 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3822 context_update_stream_info(context, state);
3824 else
3826 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3828 if (map & 1)
3829 wined3d_buffer_load(state->streams[context->stream_info.elements[i].stream_idx].buffer,
3830 context, state);
3832 /* Loading the buffers above may have invalidated the stream info. */
3833 if (isStateDirty(context, STATE_STREAMSRC))
3834 context_update_stream_info(context, state);
3836 if (state->index_buffer)
3838 if (context->stream_info.all_vbo)
3839 wined3d_buffer_load(state->index_buffer, context, state);
3840 else
3841 wined3d_buffer_load_sysmem(state->index_buffer, context);
3844 for (i = 0; i < context->numDirtyEntries; ++i)
3846 DWORD rep = context->dirtyArray[i];
3847 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3848 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3849 context->isStateDirty[idx] &= ~(1u << shift);
3850 state_table[rep].apply(context, state, rep);
3853 if (context->shader_update_mask & ~(1u << WINED3D_SHADER_TYPE_COMPUTE))
3855 device->shader_backend->shader_select(device->shader_priv, context, state);
3856 context->shader_update_mask &= 1u << WINED3D_SHADER_TYPE_COMPUTE;
3859 if (context->constant_update_mask)
3861 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3862 context->constant_update_mask = 0;
3865 if (context->update_shader_resource_bindings)
3867 for (i = 0; i < WINED3D_SHADER_TYPE_GRAPHICS_COUNT; ++i)
3868 context_bind_shader_resources(context, state, i);
3869 context->update_shader_resource_bindings = 0;
3870 if (gl_info->limits.combined_samplers == gl_info->limits.graphics_samplers)
3871 context->update_compute_shader_resource_bindings = 1;
3874 if (context->update_unordered_access_view_bindings)
3876 context_bind_unordered_access_views(context,
3877 state->shader[WINED3D_SHADER_TYPE_PIXEL],
3878 state->unordered_access_view[WINED3D_PIPELINE_GRAPHICS]);
3879 context->update_unordered_access_view_bindings = 0;
3880 context->update_compute_unordered_access_view_bindings = 1;
3883 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3885 context_check_fbo_status(context, GL_FRAMEBUFFER);
3888 context->numDirtyEntries = 0; /* This makes the whole list clean */
3889 context->last_was_blit = FALSE;
3891 return TRUE;
3894 void context_apply_compute_state(struct wined3d_context *context,
3895 const struct wined3d_device *device, const struct wined3d_state *state)
3897 const struct StateEntry *state_table = context->state_table;
3898 const struct wined3d_gl_info *gl_info = context->gl_info;
3899 unsigned int state_id, i, j;
3901 context_load_shader_resources(context, state, 1u << WINED3D_SHADER_TYPE_COMPUTE);
3902 context_load_unordered_access_resources(context, state->shader[WINED3D_SHADER_TYPE_COMPUTE],
3903 state->unordered_access_view[WINED3D_PIPELINE_COMPUTE]);
3905 for (i = 0, state_id = STATE_COMPUTE_OFFSET; i < ARRAY_SIZE(context->dirty_compute_states); ++i)
3907 for (j = 0; j < sizeof(*context->dirty_compute_states) * CHAR_BIT; ++j, ++state_id)
3909 if (context->dirty_compute_states[i] & (1u << j))
3910 state_table[state_id].apply(context, state, state_id);
3913 memset(context->dirty_compute_states, 0, sizeof(*context->dirty_compute_states));
3915 if (context->shader_update_mask & (1u << WINED3D_SHADER_TYPE_COMPUTE))
3917 device->shader_backend->shader_select_compute(device->shader_priv, context, state);
3918 context->shader_update_mask &= ~(1u << WINED3D_SHADER_TYPE_COMPUTE);
3921 if (context->update_compute_shader_resource_bindings)
3923 context_bind_shader_resources(context, state, WINED3D_SHADER_TYPE_COMPUTE);
3924 context->update_compute_shader_resource_bindings = 0;
3925 if (gl_info->limits.combined_samplers == gl_info->limits.graphics_samplers)
3926 context->update_shader_resource_bindings = 1;
3929 if (context->update_compute_unordered_access_view_bindings)
3931 context_bind_unordered_access_views(context,
3932 state->shader[WINED3D_SHADER_TYPE_COMPUTE],
3933 state->unordered_access_view[WINED3D_PIPELINE_COMPUTE]);
3934 context->update_compute_unordered_access_view_bindings = 0;
3935 context->update_unordered_access_view_bindings = 1;
3938 context->last_was_blit = FALSE;
3941 void context_end_transform_feedback(struct wined3d_context *context)
3943 const struct wined3d_gl_info *gl_info = context->gl_info;
3944 if (context->transform_feedback_active)
3946 GL_EXTCALL(glEndTransformFeedback());
3947 checkGLcall("glEndTransformFeedback");
3948 context->transform_feedback_active = 0;
3949 context->transform_feedback_paused = 0;
3953 static void context_setup_target(struct wined3d_context *context,
3954 struct wined3d_texture *texture, unsigned int sub_resource_idx)
3956 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
3958 render_offscreen = wined3d_resource_is_offscreen(&texture->resource);
3959 if (context->current_rt.texture == texture
3960 && context->current_rt.sub_resource_idx == sub_resource_idx
3961 && render_offscreen == old_render_offscreen)
3962 return;
3964 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
3965 * the alpha blend state changes with different render target formats. */
3966 if (!context->current_rt.texture)
3968 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3970 else
3972 const struct wined3d_format *old = context->current_rt.texture->resource.format;
3973 const struct wined3d_format *new = texture->resource.format;
3975 if (old->id != new->id)
3977 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
3978 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
3979 || !(texture->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
3980 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3982 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
3983 if ((context->current_rt.texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
3984 != (texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
3985 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3988 /* When switching away from an offscreen render target, and we're not
3989 * using FBOs, we have to read the drawable into the texture. This is
3990 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
3991 * There are some things that need care though. PreLoad needs a GL context,
3992 * and FindContext is called before the context is activated. It also
3993 * has to be called with the old rendertarget active, otherwise a
3994 * wrong drawable is read. */
3995 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
3996 && old_render_offscreen && (context->current_rt.texture != texture
3997 || context->current_rt.sub_resource_idx != sub_resource_idx))
3999 unsigned int prev_sub_resource_idx = context->current_rt.sub_resource_idx;
4000 struct wined3d_texture *prev_texture = context->current_rt.texture;
4002 /* Read the back buffer of the old drawable into the destination texture. */
4003 if (prev_texture->texture_srgb.name)
4004 wined3d_texture_load(prev_texture, context, TRUE);
4005 wined3d_texture_load(prev_texture, context, FALSE);
4006 wined3d_texture_invalidate_location(prev_texture, prev_sub_resource_idx, WINED3D_LOCATION_DRAWABLE);
4010 context->current_rt.texture = texture;
4011 context->current_rt.sub_resource_idx = sub_resource_idx;
4012 context_set_render_offscreen(context, render_offscreen);
4015 struct wined3d_context *context_acquire(const struct wined3d_device *device,
4016 struct wined3d_texture *texture, unsigned int sub_resource_idx)
4018 struct wined3d_context *current_context = context_get_current();
4019 struct wined3d_context *context;
4020 BOOL swapchain_texture;
4022 TRACE("device %p, texture %p, sub_resource_idx %u.\n", device, texture, sub_resource_idx);
4024 wined3d_from_cs(device->cs);
4026 if (current_context && current_context->destroyed)
4027 current_context = NULL;
4029 swapchain_texture = texture && texture->swapchain;
4030 if (!texture)
4032 if (current_context
4033 && current_context->current_rt.texture
4034 && current_context->device == device)
4036 texture = current_context->current_rt.texture;
4037 sub_resource_idx = current_context->current_rt.sub_resource_idx;
4039 else
4041 struct wined3d_swapchain *swapchain = device->swapchains[0];
4043 if (swapchain->back_buffers)
4044 texture = swapchain->back_buffers[0];
4045 else
4046 texture = swapchain->front_buffer;
4047 sub_resource_idx = 0;
4051 if (current_context && current_context->current_rt.texture == texture)
4053 context = current_context;
4055 else if (swapchain_texture)
4057 TRACE("Rendering onscreen.\n");
4059 context = swapchain_get_context(texture->swapchain);
4061 else
4063 TRACE("Rendering offscreen.\n");
4065 /* Stay with the current context if possible. Otherwise use the
4066 * context for the primary swapchain. */
4067 if (current_context && current_context->device == device)
4068 context = current_context;
4069 else
4070 context = swapchain_get_context(device->swapchains[0]);
4073 context_enter(context);
4074 context_update_window(context);
4075 context_setup_target(context, texture, sub_resource_idx);
4076 if (!context->valid)
4077 return context;
4079 if (context != current_context)
4081 if (!context_set_current(context))
4082 ERR("Failed to activate the new context.\n");
4084 else if (context->needs_set)
4086 context_set_gl_context(context);
4089 return context;
4092 struct wined3d_context *context_reacquire(const struct wined3d_device *device,
4093 struct wined3d_context *context)
4095 struct wined3d_context *current_context;
4097 if (!context || context->tid != GetCurrentThreadId())
4098 return NULL;
4100 current_context = context_acquire(device, context->current_rt.texture,
4101 context->current_rt.sub_resource_idx);
4102 if (current_context != context)
4103 ERR("Acquired context %p instead of %p.\n", current_context, context);
4104 return current_context;