bcrypt: Add support for AES encryption on macOS.
[wine.git] / dlls / wined3d / context.c
blob23f63aacda217ee0d79f736226201b94b1318fd1
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 < ARRAY_SIZE(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_fence(struct wined3d_context *context, struct wined3d_fence *fence)
799 const struct wined3d_gl_info *gl_info = context->gl_info;
801 if (context->free_fence_count)
803 fence->object = context->free_fences[--context->free_fence_count];
805 else
807 if (gl_info->supported[ARB_SYNC])
809 /* Using ARB_sync, not much to do here. */
810 fence->object.sync = NULL;
811 TRACE("Allocated sync object in context %p.\n", context);
813 else if (gl_info->supported[APPLE_FENCE])
815 GL_EXTCALL(glGenFencesAPPLE(1, &fence->object.id));
816 checkGLcall("glGenFencesAPPLE");
818 TRACE("Allocated fence %u in context %p.\n", fence->object.id, context);
820 else if(gl_info->supported[NV_FENCE])
822 GL_EXTCALL(glGenFencesNV(1, &fence->object.id));
823 checkGLcall("glGenFencesNV");
825 TRACE("Allocated fence %u in context %p.\n", fence->object.id, context);
827 else
829 WARN("Fences not supported, not allocating fence.\n");
830 fence->object.id = 0;
834 fence->context = context;
835 list_add_head(&context->fences, &fence->entry);
838 void context_free_fence(struct wined3d_fence *fence)
840 struct wined3d_context *context = fence->context;
842 list_remove(&fence->entry);
843 fence->context = NULL;
845 if (!wined3d_array_reserve((void **)&context->free_fences,
846 &context->free_fence_size, context->free_fence_count + 1,
847 sizeof(*context->free_fences)))
849 ERR("Failed to grow free list, leaking fence %u in context %p.\n", fence->object.id, context);
850 return;
853 context->free_fences[context->free_fence_count++] = fence->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)
1099 const struct wined3d_gl_info *gl_info = context->gl_info;
1100 BOOL private = context->hdc_is_private;
1101 int format = context->pixel_format;
1102 HDC dc = context->hdc;
1103 int current;
1105 if (private && context->hdc_has_format)
1106 return TRUE;
1108 if (!private && WindowFromDC(dc) != context->win_handle)
1109 return FALSE;
1111 current = gl_info->gl_ops.wgl.p_wglGetPixelFormat(dc);
1112 if (current == format) goto success;
1114 if (!current)
1116 if (!SetPixelFormat(dc, format, NULL))
1118 /* This may also happen if the dc belongs to a destroyed window. */
1119 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
1120 format, dc, GetLastError());
1121 return FALSE;
1124 context->restore_pf = 0;
1125 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
1126 goto success;
1129 /* By default WGL doesn't allow pixel format adjustments but we need it
1130 * here. For this reason there's a Wine specific wglSetPixelFormat()
1131 * which allows us to set the pixel format multiple times. Only use it
1132 * when really needed. */
1133 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
1135 HWND win;
1137 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
1139 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
1140 format, dc);
1141 return FALSE;
1144 win = private ? NULL : WindowFromDC(dc);
1145 if (win != context->restore_pf_win)
1147 context_restore_pixel_format(context);
1149 context->restore_pf = private ? 0 : current;
1150 context->restore_pf_win = win;
1153 goto success;
1156 /* OpenGL doesn't allow pixel format adjustments. Print an error and
1157 * continue using the old format. There's a big chance that the old
1158 * format works although with a performance hit and perhaps rendering
1159 * errors. */
1160 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
1161 format, dc, current);
1162 return TRUE;
1164 success:
1165 if (private)
1166 context->hdc_has_format = TRUE;
1167 return TRUE;
1170 static BOOL context_set_gl_context(struct wined3d_context *ctx)
1172 struct wined3d_swapchain *swapchain = ctx->swapchain;
1173 BOOL backup = FALSE;
1175 if (!context_set_pixel_format(ctx))
1177 WARN("Failed to set pixel format %d on device context %p.\n",
1178 ctx->pixel_format, ctx->hdc);
1179 backup = TRUE;
1182 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
1184 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
1185 ctx->glCtx, ctx->hdc, GetLastError());
1186 ctx->valid = 0;
1187 WARN("Trying fallback to the backup window.\n");
1189 /* FIXME: If the context is destroyed it's no longer associated with
1190 * a swapchain, so we can't use the swapchain to get a backup dc. To
1191 * make this work windowless contexts would need to be handled by the
1192 * device. */
1193 if (ctx->destroyed || !swapchain)
1195 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
1196 context_set_current(NULL);
1197 return FALSE;
1200 if (!(ctx->hdc = swapchain_get_backup_dc(swapchain)))
1202 context_set_current(NULL);
1203 return FALSE;
1206 ctx->hdc_is_private = TRUE;
1207 ctx->hdc_has_format = FALSE;
1209 if (!context_set_pixel_format(ctx))
1211 ERR("Failed to set pixel format %d on device context %p.\n",
1212 ctx->pixel_format, ctx->hdc);
1213 context_set_current(NULL);
1214 return FALSE;
1217 if (!wglMakeCurrent(ctx->hdc, ctx->glCtx))
1219 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
1220 ctx->hdc, GetLastError());
1221 context_set_current(NULL);
1222 return FALSE;
1225 ctx->valid = 1;
1227 ctx->needs_set = 0;
1228 return TRUE;
1231 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
1233 if (!wglMakeCurrent(dc, gl_ctx))
1235 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1236 gl_ctx, dc, GetLastError());
1237 context_set_current(NULL);
1241 static void context_update_window(struct wined3d_context *context)
1243 if (!context->swapchain)
1244 return;
1246 if (context->win_handle == context->swapchain->win_handle)
1247 return;
1249 TRACE("Updating context %p window from %p to %p.\n",
1250 context, context->win_handle, context->swapchain->win_handle);
1252 if (context->hdc)
1253 wined3d_release_dc(context->win_handle, context->hdc);
1255 context->win_handle = context->swapchain->win_handle;
1256 context->hdc_is_private = FALSE;
1257 context->hdc_has_format = FALSE;
1258 context->needs_set = 1;
1259 context->valid = 1;
1261 if (!(context->hdc = GetDCEx(context->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1263 ERR("Failed to get a device context for window %p.\n", context->win_handle);
1264 context->valid = 0;
1268 static void context_destroy_gl_resources(struct wined3d_context *context)
1270 struct wined3d_pipeline_statistics_query *pipeline_statistics_query;
1271 const struct wined3d_gl_info *gl_info = context->gl_info;
1272 struct wined3d_so_statistics_query *so_statistics_query;
1273 struct wined3d_timestamp_query *timestamp_query;
1274 struct wined3d_occlusion_query *occlusion_query;
1275 struct fbo_entry *entry, *entry2;
1276 struct wined3d_fence *fence;
1277 HGLRC restore_ctx;
1278 HDC restore_dc;
1279 unsigned int i;
1281 restore_ctx = wglGetCurrentContext();
1282 restore_dc = wglGetCurrentDC();
1284 if (restore_ctx == context->glCtx)
1285 restore_ctx = NULL;
1286 else if (context->valid)
1287 context_set_gl_context(context);
1289 LIST_FOR_EACH_ENTRY(so_statistics_query, &context->so_statistics_queries,
1290 struct wined3d_so_statistics_query, entry)
1292 if (context->valid)
1293 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(so_statistics_query->u.id), so_statistics_query->u.id));
1294 so_statistics_query->context = NULL;
1297 LIST_FOR_EACH_ENTRY(pipeline_statistics_query, &context->pipeline_statistics_queries,
1298 struct wined3d_pipeline_statistics_query, entry)
1300 if (context->valid)
1301 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(pipeline_statistics_query->u.id), pipeline_statistics_query->u.id));
1302 pipeline_statistics_query->context = NULL;
1305 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
1307 if (context->valid)
1308 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
1309 timestamp_query->context = NULL;
1312 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1314 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1315 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1316 occlusion_query->context = NULL;
1319 LIST_FOR_EACH_ENTRY(fence, &context->fences, struct wined3d_fence, entry)
1321 if (context->valid)
1323 if (gl_info->supported[ARB_SYNC])
1325 if (fence->object.sync)
1326 GL_EXTCALL(glDeleteSync(fence->object.sync));
1328 else if (gl_info->supported[APPLE_FENCE])
1330 GL_EXTCALL(glDeleteFencesAPPLE(1, &fence->object.id));
1332 else if (gl_info->supported[NV_FENCE])
1334 GL_EXTCALL(glDeleteFencesNV(1, &fence->object.id));
1337 fence->context = NULL;
1340 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1342 if (!context->valid) entry->id = 0;
1343 context_destroy_fbo_entry(context, entry);
1346 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1348 if (!context->valid) entry->id = 0;
1349 context_destroy_fbo_entry(context, entry);
1352 if (context->valid)
1354 if (context->dummy_arbfp_prog)
1356 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1359 if (gl_info->supported[WINED3D_GL_PRIMITIVE_QUERY])
1361 for (i = 0; i < context->free_so_statistics_query_count; ++i)
1363 union wined3d_gl_so_statistics_query *q = &context->free_so_statistics_queries[i];
1364 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(q->id), q->id));
1368 if (gl_info->supported[ARB_PIPELINE_STATISTICS_QUERY])
1370 for (i = 0; i < context->free_pipeline_statistics_query_count; ++i)
1372 union wined3d_gl_pipeline_statistics_query *q = &context->free_pipeline_statistics_queries[i];
1373 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(q->id), q->id));
1377 if (gl_info->supported[ARB_TIMER_QUERY])
1378 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1380 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1381 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1383 if (gl_info->supported[ARB_SYNC])
1385 for (i = 0; i < context->free_fence_count; ++i)
1387 GL_EXTCALL(glDeleteSync(context->free_fences[i].sync));
1390 else if (gl_info->supported[APPLE_FENCE])
1392 for (i = 0; i < context->free_fence_count; ++i)
1394 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_fences[i].id));
1397 else if (gl_info->supported[NV_FENCE])
1399 for (i = 0; i < context->free_fence_count; ++i)
1401 GL_EXTCALL(glDeleteFencesNV(1, &context->free_fences[i].id));
1405 checkGLcall("context cleanup");
1408 HeapFree(GetProcessHeap(), 0, context->free_so_statistics_queries);
1409 HeapFree(GetProcessHeap(), 0, context->free_pipeline_statistics_queries);
1410 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1411 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1412 HeapFree(GetProcessHeap(), 0, context->free_fences);
1414 context_restore_pixel_format(context);
1415 if (restore_ctx)
1417 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1419 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1421 ERR("Failed to disable GL context.\n");
1424 wined3d_release_dc(context->win_handle, context->hdc);
1426 if (!wglDeleteContext(context->glCtx))
1428 DWORD err = GetLastError();
1429 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1433 DWORD context_get_tls_idx(void)
1435 return wined3d_context_tls_idx;
1438 void context_set_tls_idx(DWORD idx)
1440 wined3d_context_tls_idx = idx;
1443 struct wined3d_context *context_get_current(void)
1445 return TlsGetValue(wined3d_context_tls_idx);
1448 BOOL context_set_current(struct wined3d_context *ctx)
1450 struct wined3d_context *old = context_get_current();
1452 if (old == ctx)
1454 TRACE("Already using D3D context %p.\n", ctx);
1455 return TRUE;
1458 if (old)
1460 if (old->destroyed)
1462 TRACE("Switching away from destroyed context %p.\n", old);
1463 context_destroy_gl_resources(old);
1464 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1465 HeapFree(GetProcessHeap(), 0, old);
1467 else
1469 if (wglGetCurrentContext())
1471 const struct wined3d_gl_info *gl_info = old->gl_info;
1472 TRACE("Flushing context %p before switching to %p.\n", old, ctx);
1473 gl_info->gl_ops.gl.p_glFlush();
1475 old->current = 0;
1479 if (ctx)
1481 if (!ctx->valid)
1483 ERR("Trying to make invalid context %p current\n", ctx);
1484 return FALSE;
1487 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1488 if (!context_set_gl_context(ctx))
1489 return FALSE;
1490 ctx->current = 1;
1492 else if (wglGetCurrentContext())
1494 TRACE("Clearing current D3D context.\n");
1495 if (!wglMakeCurrent(NULL, NULL))
1497 DWORD err = GetLastError();
1498 ERR("Failed to clear current GL context, last error %#x.\n", err);
1499 TlsSetValue(wined3d_context_tls_idx, NULL);
1500 return FALSE;
1504 return TlsSetValue(wined3d_context_tls_idx, ctx);
1507 void context_release(struct wined3d_context *context)
1509 TRACE("Releasing context %p, level %u.\n", context, context->level);
1511 if (WARN_ON(d3d))
1513 if (!context->level)
1514 WARN("Context %p is not active.\n", context);
1515 else if (context != context_get_current())
1516 WARN("Context %p is not the current context.\n", context);
1519 if (!--context->level)
1521 if (context_restore_pixel_format(context))
1522 context->needs_set = 1;
1523 if (context->restore_ctx)
1525 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1526 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1527 context->restore_ctx = NULL;
1528 context->restore_dc = NULL;
1531 if (context->destroy_delayed)
1533 TRACE("Destroying context %p.\n", context);
1534 context_destroy(context->device, context);
1539 /* This is used when a context for render target A is active, but a separate context is
1540 * needed to access the WGL framebuffer for render target B. Re-acquire a context for rt
1541 * A to avoid breaking caller code. */
1542 void context_restore(struct wined3d_context *context, struct wined3d_surface *restore)
1544 if (context->current_rt.texture != restore->container
1545 || context->current_rt.sub_resource_idx != surface_get_sub_resource_idx(restore))
1547 context_release(context);
1548 context = context_acquire(restore->container->resource.device,
1549 restore->container, surface_get_sub_resource_idx(restore));
1552 context_release(context);
1555 static void context_enter(struct wined3d_context *context)
1557 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1559 if (!context->level++)
1561 const struct wined3d_context *current_context = context_get_current();
1562 HGLRC current_gl = wglGetCurrentContext();
1564 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1566 TRACE("Another GL context (%p on device context %p) is already current.\n",
1567 current_gl, wglGetCurrentDC());
1568 context->restore_ctx = current_gl;
1569 context->restore_dc = wglGetCurrentDC();
1570 context->needs_set = 1;
1572 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1573 && context->pixel_format != context->gl_info->gl_ops.wgl.p_wglGetPixelFormat(context->hdc))
1574 context->needs_set = 1;
1578 void context_invalidate_compute_state(struct wined3d_context *context, DWORD state_id)
1580 DWORD representative = context->state_table[state_id].representative - STATE_COMPUTE_OFFSET;
1581 unsigned int index, shift;
1583 index = representative / (sizeof(*context->dirty_compute_states) * CHAR_BIT);
1584 shift = representative & (sizeof(*context->dirty_compute_states) * CHAR_BIT - 1);
1585 context->dirty_compute_states[index] |= (1u << shift);
1588 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1590 DWORD rep = context->state_table[state].representative;
1591 DWORD idx;
1592 BYTE shift;
1594 if (isStateDirty(context, rep)) return;
1596 context->dirtyArray[context->numDirtyEntries++] = rep;
1597 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1598 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1599 context->isStateDirty[idx] |= (1u << shift);
1602 /* This function takes care of wined3d pixel format selection. */
1603 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1604 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1605 BOOL auxBuffers)
1607 unsigned int cfg_count = device->adapter->cfg_count;
1608 unsigned int current_value;
1609 PIXELFORMATDESCRIPTOR pfd;
1610 int iPixelFormat = 0;
1611 unsigned int i;
1613 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x.\n",
1614 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1615 auxBuffers);
1617 current_value = 0;
1618 for (i = 0; i < cfg_count; ++i)
1620 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1621 unsigned int value;
1623 /* For now only accept RGBA formats. Perhaps some day we will
1624 * allow floating point formats for pbuffers. */
1625 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1626 continue;
1627 /* In window mode we need a window drawable format and double buffering. */
1628 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1629 continue;
1630 if (cfg->redSize < color_format->red_size)
1631 continue;
1632 if (cfg->greenSize < color_format->green_size)
1633 continue;
1634 if (cfg->blueSize < color_format->blue_size)
1635 continue;
1636 if (cfg->alphaSize < color_format->alpha_size)
1637 continue;
1638 if (cfg->depthSize < ds_format->depth_size)
1639 continue;
1640 if (ds_format->stencil_size && cfg->stencilSize != ds_format->stencil_size)
1641 continue;
1642 /* Check multisampling support. */
1643 if (cfg->numSamples)
1644 continue;
1646 value = 1;
1647 /* We try to locate a format which matches our requirements exactly. In case of
1648 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1649 if (cfg->depthSize == ds_format->depth_size)
1650 value += 1;
1651 if (cfg->stencilSize == ds_format->stencil_size)
1652 value += 2;
1653 if (cfg->alphaSize == color_format->alpha_size)
1654 value += 4;
1655 /* We like to have aux buffers in backbuffer mode */
1656 if (auxBuffers && cfg->auxBuffers)
1657 value += 8;
1658 if (cfg->redSize == color_format->red_size
1659 && cfg->greenSize == color_format->green_size
1660 && cfg->blueSize == color_format->blue_size)
1661 value += 16;
1663 if (value > current_value)
1665 iPixelFormat = cfg->iPixelFormat;
1666 current_value = value;
1670 if (!iPixelFormat)
1672 ERR("Trying to locate a compatible pixel format because an exact match failed.\n");
1674 memset(&pfd, 0, sizeof(pfd));
1675 pfd.nSize = sizeof(pfd);
1676 pfd.nVersion = 1;
1677 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1678 pfd.iPixelType = PFD_TYPE_RGBA;
1679 pfd.cAlphaBits = color_format->alpha_size;
1680 pfd.cColorBits = color_format->red_size + color_format->green_size
1681 + color_format->blue_size + color_format->alpha_size;
1682 pfd.cDepthBits = ds_format->depth_size;
1683 pfd.cStencilBits = ds_format->stencil_size;
1684 pfd.iLayerType = PFD_MAIN_PLANE;
1686 if (!(iPixelFormat = ChoosePixelFormat(hdc, &pfd)))
1688 /* Something is very wrong as ChoosePixelFormat() barely fails. */
1689 ERR("Can't find a suitable pixel format.\n");
1690 return 0;
1694 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s.\n",
1695 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1696 return iPixelFormat;
1699 /* Context activation is done by the caller. */
1700 void context_bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1702 const struct wined3d_gl_info *gl_info = context->gl_info;
1703 unsigned int i;
1705 for (i = 0; i < gl_info->limits.combined_samplers; ++i)
1707 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1708 checkGLcall("glActiveTexture");
1710 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_textures.tex_2d);
1712 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1713 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_textures.tex_rect);
1715 if (gl_info->supported[EXT_TEXTURE3D])
1716 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_textures.tex_3d);
1718 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1719 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_textures.tex_cube);
1721 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP_ARRAY])
1722 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, device->dummy_textures.tex_cube_array);
1724 if (gl_info->supported[EXT_TEXTURE_ARRAY])
1725 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, device->dummy_textures.tex_2d_array);
1727 if (gl_info->supported[ARB_TEXTURE_BUFFER_OBJECT])
1728 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_BUFFER, device->dummy_textures.tex_buffer);
1730 checkGLcall("Bind dummy textures");
1734 void wined3d_check_gl_call(const struct wined3d_gl_info *gl_info,
1735 const char *file, unsigned int line, const char *name)
1737 GLint err;
1739 if (gl_info->supported[ARB_DEBUG_OUTPUT] || (err = gl_info->gl_ops.gl.p_glGetError()) == GL_NO_ERROR)
1741 TRACE("%s call ok %s / %u.\n", name, file, line);
1742 return;
1747 ERR(">>>>>>> %s (%#x) from %s @ %s / %u.\n",
1748 debug_glerror(err), err, name, file,line);
1749 err = gl_info->gl_ops.gl.p_glGetError();
1750 } while (err != GL_NO_ERROR);
1753 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1755 return gl_info->supported[ARB_DEBUG_OUTPUT]
1756 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1759 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1760 GLenum severity, GLsizei length, const char *message, void *ctx)
1762 switch (type)
1764 case GL_DEBUG_TYPE_ERROR_ARB:
1765 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1766 break;
1768 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1769 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1770 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1771 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1772 break;
1774 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1775 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1776 break;
1778 default:
1779 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1780 break;
1784 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1786 HGLRC ctx;
1787 unsigned int ctx_attrib_idx = 0;
1788 GLint ctx_attribs[7], ctx_flags = 0;
1790 if (context_debug_output_enabled(gl_info))
1791 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1792 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1793 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1794 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1795 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1796 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1797 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1798 if (ctx_flags)
1800 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1801 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1803 ctx_attribs[ctx_attrib_idx] = 0;
1805 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1807 if (ctx_flags & WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
1809 ctx_attribs[ctx_attrib_idx - 1] &= ~WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1810 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1811 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1812 GetLastError());
1815 return ctx;
1818 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1819 struct wined3d_texture *target, const struct wined3d_format *ds_format)
1821 struct wined3d_device *device = swapchain->device;
1822 const struct wined3d_d3d_info *d3d_info = &device->adapter->d3d_info;
1823 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1824 const struct wined3d_format *color_format;
1825 struct wined3d_context *ret;
1826 BOOL auxBuffers = FALSE;
1827 HGLRC ctx, share_ctx;
1828 DWORD target_usage;
1829 unsigned int i;
1830 DWORD state;
1832 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1834 wined3d_from_cs(device->cs);
1836 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1837 if (!ret)
1838 return NULL;
1840 if (!(ret->blit_targets = wined3d_calloc(gl_info->limits.buffers, sizeof(*ret->blit_targets))))
1841 goto out;
1843 if (!(ret->draw_buffers = wined3d_calloc(gl_info->limits.buffers, sizeof(*ret->draw_buffers))))
1844 goto out;
1846 ret->fbo_key = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1847 FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[gl_info->limits.buffers + 1]));
1848 if (!ret->fbo_key)
1849 goto out;
1851 ret->free_timestamp_query_size = 4;
1852 if (!(ret->free_timestamp_queries = wined3d_calloc(ret->free_timestamp_query_size,
1853 sizeof(*ret->free_timestamp_queries))))
1854 goto out;
1855 list_init(&ret->timestamp_queries);
1857 ret->free_occlusion_query_size = 4;
1858 if (!(ret->free_occlusion_queries = wined3d_calloc(ret->free_occlusion_query_size,
1859 sizeof(*ret->free_occlusion_queries))))
1860 goto out;
1861 list_init(&ret->occlusion_queries);
1863 ret->free_fence_size = 4;
1864 if (!(ret->free_fences = wined3d_calloc(ret->free_fence_size, sizeof(*ret->free_fences))))
1865 goto out;
1866 list_init(&ret->fences);
1868 list_init(&ret->so_statistics_queries);
1870 list_init(&ret->pipeline_statistics_queries);
1872 list_init(&ret->fbo_list);
1873 list_init(&ret->fbo_destroy_list);
1875 if (!device->shader_backend->shader_allocate_context_data(ret))
1877 ERR("Failed to allocate shader backend context data.\n");
1878 goto out;
1880 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1882 ERR("Failed to allocate fragment pipeline context data.\n");
1883 goto out;
1886 for (i = 0; i < ARRAY_SIZE(ret->tex_unit_map); ++i)
1887 ret->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
1888 for (i = 0; i < ARRAY_SIZE(ret->rev_tex_unit_map); ++i)
1889 ret->rev_tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
1890 if (gl_info->limits.graphics_samplers >= MAX_COMBINED_SAMPLERS)
1892 /* Initialize the texture unit mapping to a 1:1 mapping. */
1893 unsigned int base, count;
1895 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, WINED3D_SHADER_TYPE_PIXEL, &base, &count);
1896 if (base + MAX_FRAGMENT_SAMPLERS > ARRAY_SIZE(ret->rev_tex_unit_map))
1898 ERR("Unexpected texture unit base index %u.\n", base);
1899 goto out;
1901 for (i = 0; i < min(count, MAX_FRAGMENT_SAMPLERS); ++i)
1903 ret->tex_unit_map[i] = base + i;
1904 ret->rev_tex_unit_map[base + i] = i;
1907 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, WINED3D_SHADER_TYPE_VERTEX, &base, &count);
1908 if (base + MAX_VERTEX_SAMPLERS > ARRAY_SIZE(ret->rev_tex_unit_map))
1910 ERR("Unexpected texture unit base index %u.\n", base);
1911 goto out;
1913 for (i = 0; i < min(count, MAX_VERTEX_SAMPLERS); ++i)
1915 ret->tex_unit_map[MAX_FRAGMENT_SAMPLERS + i] = base + i;
1916 ret->rev_tex_unit_map[base + i] = MAX_FRAGMENT_SAMPLERS + i;
1920 if (!(ret->texture_type = wined3d_calloc(gl_info->limits.combined_samplers,
1921 sizeof(*ret->texture_type))))
1922 goto out;
1924 if (!(ret->hdc = GetDCEx(swapchain->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1926 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1928 if ((ret->hdc = swapchain_get_backup_dc(swapchain)))
1929 ret->hdc_is_private = TRUE;
1930 else
1932 ERR("Failed to retrieve a device context.\n");
1933 goto out;
1937 color_format = target->resource.format;
1938 target_usage = target->resource.usage;
1940 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1941 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1942 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1944 auxBuffers = TRUE;
1946 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1947 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM, target_usage);
1948 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1949 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1952 /* DirectDraw supports 8bit paletted render targets and these are used by
1953 * old games like StarCraft and C&C. Most modern hardware doesn't support
1954 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1955 * conversion (ab)uses the alpha component for storing the palette index.
1956 * For this reason we require a format with 8bit alpha, so request
1957 * A8R8G8B8. */
1958 if (color_format->id == WINED3DFMT_P8_UINT)
1959 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1961 /* When using FBOs for off-screen rendering, we only use the drawable for
1962 * presentation blits, and don't do any rendering to it. That means we
1963 * don't need depth or stencil buffers, and can mostly ignore the render
1964 * target format. This wouldn't necessarily be quite correct for 10bpc
1965 * display modes, but we don't currently support those.
1966 * Using the same format regardless of the color/depth/stencil targets
1967 * makes it much less likely that different wined3d instances will set
1968 * conflicting pixel formats. */
1969 if (wined3d_settings.offscreen_rendering_mode != ORM_BACKBUFFER)
1971 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1972 ds_format = wined3d_get_format(gl_info, WINED3DFMT_UNKNOWN, WINED3DUSAGE_DEPTHSTENCIL);
1975 /* Try to find a pixel format which matches our requirements. */
1976 if (!(ret->pixel_format = context_choose_pixel_format(device, ret->hdc, color_format, ds_format, auxBuffers)))
1977 goto out;
1979 ret->gl_info = gl_info;
1980 ret->win_handle = swapchain->win_handle;
1982 context_enter(ret);
1984 if (!context_set_pixel_format(ret))
1986 ERR("Failed to set pixel format %d on device context %p.\n", ret->pixel_format, ret->hdc);
1987 context_release(ret);
1988 goto out;
1991 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1992 if (gl_info->p_wglCreateContextAttribsARB)
1994 if (!(ctx = context_create_wgl_attribs(gl_info, ret->hdc, share_ctx)))
1995 goto out;
1997 else
1999 if (!(ctx = wglCreateContext(ret->hdc)))
2001 ERR("Failed to create a WGL context.\n");
2002 context_release(ret);
2003 goto out;
2006 if (share_ctx && !wglShareLists(share_ctx, ctx))
2008 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
2009 context_release(ret);
2010 if (!wglDeleteContext(ctx))
2011 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
2012 goto out;
2016 if (!device_context_add(device, ret))
2018 ERR("Failed to add the newly created context to the context list\n");
2019 context_release(ret);
2020 if (!wglDeleteContext(ctx))
2021 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
2022 goto out;
2025 ret->d3d_info = d3d_info;
2026 ret->state_table = device->StateTable;
2028 /* Mark all states dirty to force a proper initialization of the states on
2029 * the first use of the context. Compute states do not need initialization. */
2030 for (state = 0; state <= STATE_HIGHEST; ++state)
2032 if (ret->state_table[state].representative && !STATE_IS_COMPUTE(state))
2033 context_invalidate_state(ret, state);
2036 ret->device = device;
2037 ret->swapchain = swapchain;
2038 ret->current_rt.texture = target;
2039 ret->current_rt.sub_resource_idx = 0;
2040 ret->tid = GetCurrentThreadId();
2042 ret->render_offscreen = wined3d_resource_is_offscreen(&target->resource);
2043 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
2044 ret->valid = 1;
2046 ret->glCtx = ctx;
2047 ret->hdc_has_format = TRUE;
2048 ret->needs_set = 1;
2050 /* Set up the context defaults */
2051 if (!context_set_current(ret))
2053 ERR("Cannot activate context to set up defaults.\n");
2054 device_context_remove(device, ret);
2055 context_release(ret);
2056 if (!wglDeleteContext(ctx))
2057 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
2058 goto out;
2061 if (context_debug_output_enabled(gl_info))
2063 GL_EXTCALL(glDebugMessageCallback(wined3d_debug_callback, ret));
2064 if (TRACE_ON(d3d_synchronous))
2065 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
2066 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
2067 if (ERR_ON(d3d))
2069 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR,
2070 GL_DONT_CARE, 0, NULL, GL_TRUE));
2072 if (FIXME_ON(d3d))
2074 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
2075 GL_DONT_CARE, 0, NULL, GL_TRUE));
2076 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
2077 GL_DONT_CARE, 0, NULL, GL_TRUE));
2078 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY,
2079 GL_DONT_CARE, 0, NULL, GL_TRUE));
2081 if (WARN_ON(d3d_perf))
2083 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE,
2084 GL_DONT_CARE, 0, NULL, GL_TRUE));
2088 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
2089 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
2091 TRACE("Setting up the screen\n");
2093 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
2095 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
2096 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
2098 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
2099 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
2101 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
2102 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
2104 else
2106 GLuint vao;
2108 GL_EXTCALL(glGenVertexArrays(1, &vao));
2109 GL_EXTCALL(glBindVertexArray(vao));
2110 checkGLcall("creating VAO");
2113 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
2114 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
2115 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
2116 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, 1);");
2118 if (gl_info->supported[ARB_VERTEX_BLEND])
2120 /* Direct3D always uses n-1 weights for n world matrices and uses
2121 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
2122 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
2123 * enabled as well. */
2124 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
2125 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
2127 if (gl_info->supported[NV_TEXTURE_SHADER2])
2129 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
2130 * the previous texture where to source the offset from is always unit - 1.
2132 for (i = 1; i < gl_info->limits.textures; ++i)
2134 context_active_texture(ret, gl_info, i);
2135 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
2136 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + i - 1);
2137 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
2140 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
2142 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
2143 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
2144 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
2145 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
2146 * is ever assigned.
2148 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
2149 * program and the dummy program is destroyed when the context is destroyed.
2151 static const char dummy_program[] =
2152 "!!ARBfp1.0\n"
2153 "MOV result.color, fragment.color.primary;\n"
2154 "END\n";
2155 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
2156 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
2157 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
2160 if (gl_info->supported[ARB_POINT_SPRITE])
2162 for (i = 0; i < gl_info->limits.textures; ++i)
2164 context_active_texture(ret, gl_info, i);
2165 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
2166 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
2170 if (gl_info->supported[ARB_PROVOKING_VERTEX])
2172 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
2174 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
2176 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
2178 if (!(d3d_info->wined3d_creation_flags & WINED3D_NO_PRIMITIVE_RESTART))
2180 if (gl_info->supported[ARB_ES3_COMPATIBILITY])
2182 gl_info->gl_ops.gl.p_glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
2183 checkGLcall("enable GL_PRIMITIVE_RESTART_FIXED_INDEX");
2185 else
2187 FIXME("OpenGL implementation does not support GL_PRIMITIVE_RESTART_FIXED_INDEX.\n");
2190 if (!(d3d_info->wined3d_creation_flags & WINED3D_LEGACY_CUBEMAP_FILTERING)
2191 && gl_info->supported[ARB_SEAMLESS_CUBE_MAP])
2193 gl_info->gl_ops.gl.p_glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
2194 checkGLcall("enable seamless cube map filtering");
2196 if (gl_info->supported[ARB_CLIP_CONTROL])
2197 GL_EXTCALL(glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT));
2198 device->shader_backend->shader_init_context_state(ret);
2199 ret->shader_update_mask = (1u << WINED3D_SHADER_TYPE_PIXEL)
2200 | (1u << WINED3D_SHADER_TYPE_VERTEX)
2201 | (1u << WINED3D_SHADER_TYPE_GEOMETRY)
2202 | (1u << WINED3D_SHADER_TYPE_HULL)
2203 | (1u << WINED3D_SHADER_TYPE_DOMAIN)
2204 | (1u << WINED3D_SHADER_TYPE_COMPUTE);
2206 /* If this happens to be the first context for the device, dummy textures
2207 * are not created yet. In that case, they will be created (and bound) by
2208 * create_dummy_textures right after this context is initialized. */
2209 if (device->dummy_textures.tex_2d)
2210 context_bind_dummy_textures(device, ret);
2212 TRACE("Created context %p.\n", ret);
2214 return ret;
2216 out:
2217 if (ret->hdc)
2218 wined3d_release_dc(swapchain->win_handle, ret->hdc);
2219 device->shader_backend->shader_free_context_data(ret);
2220 device->adapter->fragment_pipe->free_context_data(ret);
2221 HeapFree(GetProcessHeap(), 0, ret->texture_type);
2222 HeapFree(GetProcessHeap(), 0, ret->free_fences);
2223 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
2224 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
2225 HeapFree(GetProcessHeap(), 0, ret->fbo_key);
2226 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
2227 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
2228 HeapFree(GetProcessHeap(), 0, ret);
2229 return NULL;
2232 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
2234 BOOL destroy;
2236 TRACE("Destroying ctx %p\n", context);
2238 wined3d_from_cs(device->cs);
2240 /* We delay destroying a context when it is active. The context_release()
2241 * function invokes context_destroy() again while leaving the last level. */
2242 if (context->level)
2244 TRACE("Delaying destruction of context %p.\n", context);
2245 context->destroy_delayed = 1;
2246 /* FIXME: Get rid of a pointer to swapchain from wined3d_context. */
2247 context->swapchain = NULL;
2248 return;
2251 if (context->tid == GetCurrentThreadId() || !context->current)
2253 context_destroy_gl_resources(context);
2254 TlsSetValue(wined3d_context_tls_idx, NULL);
2255 destroy = TRUE;
2257 else
2259 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
2260 in wined3d_adapter may go away in the meantime */
2261 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
2262 *gl_info = *context->gl_info;
2263 context->gl_info = gl_info;
2264 context->destroyed = 1;
2265 destroy = FALSE;
2268 device->shader_backend->shader_free_context_data(context);
2269 device->adapter->fragment_pipe->free_context_data(context);
2270 HeapFree(GetProcessHeap(), 0, context->texture_type);
2271 HeapFree(GetProcessHeap(), 0, context->fbo_key);
2272 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
2273 HeapFree(GetProcessHeap(), 0, context->blit_targets);
2274 device_context_remove(device, context);
2275 if (destroy) HeapFree(GetProcessHeap(), 0, context);
2278 const DWORD *context_get_tex_unit_mapping(const struct wined3d_context *context,
2279 const struct wined3d_shader_version *shader_version, unsigned int *base, unsigned int *count)
2281 const struct wined3d_gl_info *gl_info = context->gl_info;
2283 if (!shader_version)
2285 *base = 0;
2286 *count = MAX_TEXTURES;
2287 return context->tex_unit_map;
2290 if (shader_version->major >= 4)
2292 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, shader_version->type, base, count);
2293 return NULL;
2296 switch (shader_version->type)
2298 case WINED3D_SHADER_TYPE_PIXEL:
2299 *base = 0;
2300 *count = MAX_FRAGMENT_SAMPLERS;
2301 break;
2302 case WINED3D_SHADER_TYPE_VERTEX:
2303 *base = MAX_FRAGMENT_SAMPLERS;
2304 *count = MAX_VERTEX_SAMPLERS;
2305 break;
2306 default:
2307 ERR("Unhandled shader type %#x.\n", shader_version->type);
2308 *base = 0;
2309 *count = 0;
2312 return context->tex_unit_map;
2315 /* Context activation is done by the caller. */
2316 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
2318 const GLdouble projection[] =
2320 2.0 / width, 0.0, 0.0, 0.0,
2321 0.0, 2.0 / height, 0.0, 0.0,
2322 0.0, 0.0, 2.0, 0.0,
2323 -1.0, -1.0, -1.0, 1.0,
2326 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
2327 checkGLcall("glMatrixMode(GL_PROJECTION)");
2328 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
2329 checkGLcall("glLoadMatrixd");
2330 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
2331 checkGLcall("glViewport");
2334 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
2336 const struct wined3d_texture *rt = context->current_rt.texture;
2337 unsigned int level;
2339 if (rt->swapchain)
2341 RECT window_size;
2343 GetClientRect(context->win_handle, &window_size);
2344 size->cx = window_size.right - window_size.left;
2345 size->cy = window_size.bottom - window_size.top;
2347 return;
2350 level = context->current_rt.sub_resource_idx % rt->level_count;
2351 size->cx = wined3d_texture_get_level_width(rt, level);
2352 size->cy = wined3d_texture_get_level_height(rt, level);
2355 void context_enable_clip_distances(struct wined3d_context *context, unsigned int enable_mask)
2357 const struct wined3d_gl_info *gl_info = context->gl_info;
2358 unsigned int clip_distance_count = gl_info->limits.user_clip_distances;
2359 unsigned int i, disable_mask, current_mask;
2361 disable_mask = ~enable_mask;
2362 enable_mask &= (1u << clip_distance_count) - 1;
2363 disable_mask &= (1u << clip_distance_count) - 1;
2364 current_mask = context->clip_distance_mask;
2365 context->clip_distance_mask = enable_mask;
2367 enable_mask &= ~current_mask;
2368 for (i = 0; enable_mask; enable_mask >>= 1, ++i)
2370 if (enable_mask & 1)
2371 gl_info->gl_ops.gl.p_glEnable(GL_CLIP_DISTANCE0 + i);
2373 disable_mask &= current_mask;
2374 for (i = 0; disable_mask; disable_mask >>= 1, ++i)
2376 if (disable_mask & 1)
2377 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_DISTANCE0 + i);
2379 checkGLcall("toggle clip distances");
2382 /*****************************************************************************
2383 * SetupForBlit
2385 * Sets up a context for DirectDraw blitting.
2386 * All texture units are disabled, texture unit 0 is set as current unit
2387 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
2388 * color writing enabled for all channels
2389 * register combiners disabled, shaders disabled
2390 * world matrix is set to identity, texture matrix 0 too
2391 * projection matrix is setup for drawing screen coordinates
2393 * Params:
2394 * This: Device to activate the context for
2395 * context: Context to setup
2397 *****************************************************************************/
2398 /* Context activation is done by the caller. */
2399 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
2401 int i;
2402 const struct wined3d_gl_info *gl_info = context->gl_info;
2403 DWORD sampler;
2404 SIZE rt_size;
2406 TRACE("Setting up context %p for blitting\n", context);
2408 context_get_rt_size(context, &rt_size);
2410 if (context->last_was_blit)
2412 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
2414 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2415 context->blit_w = rt_size.cx;
2416 context->blit_h = rt_size.cy;
2417 /* No need to dirtify here, the states are still dirtified because
2418 * they weren't applied since the last SetupForBlit() call. */
2420 TRACE("Context is already set up for blitting, nothing to do\n");
2421 return;
2423 context->last_was_blit = TRUE;
2425 /* Disable all textures. The caller can then bind a texture it wants to blit
2426 * from
2428 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
2429 * function texture unit. No need to care for higher samplers
2431 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
2433 sampler = context->rev_tex_unit_map[i];
2434 context_active_texture(context, gl_info, i);
2436 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2438 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2439 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2441 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2442 checkGLcall("glDisable GL_TEXTURE_3D");
2443 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2445 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2446 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2448 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2449 checkGLcall("glDisable GL_TEXTURE_2D");
2451 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2452 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
2454 if (sampler != WINED3D_UNMAPPED_STAGE)
2456 if (sampler < MAX_TEXTURES)
2457 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2458 context_invalidate_state(context, STATE_SAMPLER(sampler));
2461 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
2462 GL_EXTCALL(glBindSampler(0, 0));
2463 context_active_texture(context, gl_info, 0);
2465 sampler = context->rev_tex_unit_map[0];
2467 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2469 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2470 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2472 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2473 checkGLcall("glDisable GL_TEXTURE_3D");
2474 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2476 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2477 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2479 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2480 checkGLcall("glDisable GL_TEXTURE_2D");
2482 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2484 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
2485 checkGLcall("glMatrixMode(GL_TEXTURE)");
2486 gl_info->gl_ops.gl.p_glLoadIdentity();
2487 checkGLcall("glLoadIdentity()");
2489 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2491 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
2492 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
2493 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
2496 if (sampler != WINED3D_UNMAPPED_STAGE)
2498 if (sampler < MAX_TEXTURES)
2500 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
2501 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2503 context_invalidate_state(context, STATE_SAMPLER(sampler));
2506 /* Other misc states */
2507 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2508 checkGLcall("glDisable(GL_ALPHA_TEST)");
2509 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2510 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2511 checkGLcall("glDisable GL_LIGHTING");
2512 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2513 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2514 checkGLcall("glDisable GL_DEPTH_TEST");
2515 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2516 glDisableWINE(GL_FOG);
2517 checkGLcall("glDisable GL_FOG");
2518 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
2519 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2520 checkGLcall("glDisable GL_BLEND");
2521 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2522 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2523 checkGLcall("glDisable GL_CULL_FACE");
2524 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2525 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2526 checkGLcall("glDisable GL_STENCIL_TEST");
2527 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2528 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2529 checkGLcall("glDisable GL_SCISSOR_TEST");
2530 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2531 if (gl_info->supported[ARB_POINT_SPRITE])
2533 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2534 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2535 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2537 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2538 checkGLcall("glColorMask");
2539 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2540 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2541 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2542 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2543 if (gl_info->supported[EXT_SECONDARY_COLOR])
2545 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2546 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2547 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2550 /* Setup transforms */
2551 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2552 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2553 gl_info->gl_ops.gl.p_glLoadIdentity();
2554 checkGLcall("glLoadIdentity()");
2555 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2557 context->last_was_rhw = TRUE;
2558 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2560 context_enable_clip_distances(context, 0);
2561 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2563 /* FIXME: Make draw_textured_quad() able to work with a upper left origin. */
2564 if (gl_info->supported[ARB_CLIP_CONTROL])
2565 GL_EXTCALL(glClipControl(GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE));
2567 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2569 /* Disable shaders */
2570 device->shader_backend->shader_disable(device->shader_priv, context);
2572 context->blit_w = rt_size.cx;
2573 context->blit_h = rt_size.cy;
2574 context_invalidate_state(context, STATE_VIEWPORT);
2575 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2578 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2580 return rt_mask & (1u << 31);
2583 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2585 return rt_mask & ~(1u << 31);
2588 /* Context activation is done by the caller. */
2589 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2591 const struct wined3d_gl_info *gl_info = context->gl_info;
2593 if (!rt_mask)
2595 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2596 checkGLcall("glDrawBuffer()");
2598 else if (is_rt_mask_onscreen(rt_mask))
2600 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2601 checkGLcall("glDrawBuffer()");
2603 else
2605 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2607 unsigned int i = 0;
2609 while (rt_mask)
2611 if (rt_mask & 1)
2612 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2613 else
2614 context->draw_buffers[i] = GL_NONE;
2616 rt_mask >>= 1;
2617 ++i;
2620 if (gl_info->supported[ARB_DRAW_BUFFERS])
2622 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2623 checkGLcall("glDrawBuffers()");
2625 else
2627 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2628 checkGLcall("glDrawBuffer()");
2631 else
2633 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2638 /* Context activation is done by the caller. */
2639 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2641 const struct wined3d_gl_info *gl_info = context->gl_info;
2642 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2643 DWORD new_mask = context_generate_rt_mask(buffer);
2645 if (new_mask == *current_mask)
2646 return;
2648 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2649 checkGLcall("glDrawBuffer()");
2651 *current_mask = new_mask;
2654 /* Context activation is done by the caller. */
2655 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2657 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2658 checkGLcall("glActiveTexture");
2659 context->active_texture = unit;
2662 void context_bind_bo(struct wined3d_context *context, GLenum binding, GLuint name)
2664 const struct wined3d_gl_info *gl_info = context->gl_info;
2666 if (binding == GL_ELEMENT_ARRAY_BUFFER)
2667 context_invalidate_state(context, STATE_INDEXBUFFER);
2669 GL_EXTCALL(glBindBuffer(binding, name));
2672 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2674 const struct wined3d_gl_info *gl_info = context->gl_info;
2675 DWORD unit = context->active_texture;
2676 DWORD old_texture_type = context->texture_type[unit];
2678 if (name)
2680 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2681 checkGLcall("glBindTexture");
2683 else
2685 target = GL_NONE;
2688 if (old_texture_type != target)
2690 const struct wined3d_device *device = context->device;
2692 switch (old_texture_type)
2694 case GL_NONE:
2695 /* nothing to do */
2696 break;
2697 case GL_TEXTURE_2D:
2698 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_textures.tex_2d);
2699 checkGLcall("glBindTexture");
2700 break;
2701 case GL_TEXTURE_2D_ARRAY:
2702 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, device->dummy_textures.tex_2d_array);
2703 checkGLcall("glBindTexture");
2704 break;
2705 case GL_TEXTURE_RECTANGLE_ARB:
2706 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_textures.tex_rect);
2707 checkGLcall("glBindTexture");
2708 break;
2709 case GL_TEXTURE_CUBE_MAP:
2710 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_textures.tex_cube);
2711 checkGLcall("glBindTexture");
2712 break;
2713 case GL_TEXTURE_CUBE_MAP_ARRAY:
2714 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, device->dummy_textures.tex_cube_array);
2715 checkGLcall("glBindTexture");
2716 break;
2717 case GL_TEXTURE_3D:
2718 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_textures.tex_3d);
2719 checkGLcall("glBindTexture");
2720 break;
2721 case GL_TEXTURE_BUFFER:
2722 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_BUFFER, device->dummy_textures.tex_buffer);
2723 checkGLcall("glBindTexture");
2724 break;
2725 default:
2726 ERR("Unexpected texture target %#x.\n", old_texture_type);
2729 context->texture_type[unit] = target;
2733 void *context_map_bo_address(struct wined3d_context *context,
2734 const struct wined3d_bo_address *data, size_t size, GLenum binding, DWORD flags)
2736 const struct wined3d_gl_info *gl_info;
2737 BYTE *memory;
2739 if (!data->buffer_object)
2740 return data->addr;
2742 gl_info = context->gl_info;
2743 context_bind_bo(context, binding, data->buffer_object);
2745 if (gl_info->supported[ARB_MAP_BUFFER_RANGE])
2747 GLbitfield map_flags = wined3d_resource_gl_map_flags(flags) & ~GL_MAP_FLUSH_EXPLICIT_BIT;
2748 memory = GL_EXTCALL(glMapBufferRange(binding, (INT_PTR)data->addr, size, map_flags));
2750 else
2752 memory = GL_EXTCALL(glMapBuffer(binding, wined3d_resource_gl_legacy_map_flags(flags)));
2753 memory += (INT_PTR)data->addr;
2756 context_bind_bo(context, binding, 0);
2757 checkGLcall("Map buffer object");
2759 return memory;
2762 void context_unmap_bo_address(struct wined3d_context *context,
2763 const struct wined3d_bo_address *data, GLenum binding)
2765 const struct wined3d_gl_info *gl_info;
2767 if (!data->buffer_object)
2768 return;
2770 gl_info = context->gl_info;
2771 context_bind_bo(context, binding, data->buffer_object);
2772 GL_EXTCALL(glUnmapBuffer(binding));
2773 context_bind_bo(context, binding, 0);
2774 checkGLcall("Unmap buffer object");
2777 void context_copy_bo_address(struct wined3d_context *context,
2778 const struct wined3d_bo_address *dst, GLenum dst_binding,
2779 const struct wined3d_bo_address *src, GLenum src_binding, size_t size)
2781 const struct wined3d_gl_info *gl_info;
2782 BYTE *dst_ptr, *src_ptr;
2784 gl_info = context->gl_info;
2786 if (dst->buffer_object && src->buffer_object)
2788 if (gl_info->supported[ARB_COPY_BUFFER])
2790 GL_EXTCALL(glBindBuffer(GL_COPY_READ_BUFFER, src->buffer_object));
2791 GL_EXTCALL(glBindBuffer(GL_COPY_WRITE_BUFFER, dst->buffer_object));
2792 GL_EXTCALL(glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER,
2793 (GLintptr)src->addr, (GLintptr)dst->addr, size));
2794 checkGLcall("direct buffer copy");
2796 else
2798 src_ptr = context_map_bo_address(context, src, size, src_binding, WINED3D_MAP_READONLY);
2799 dst_ptr = context_map_bo_address(context, dst, size, dst_binding, 0);
2801 memcpy(dst_ptr, src_ptr, size);
2803 context_unmap_bo_address(context, dst, dst_binding);
2804 context_unmap_bo_address(context, src, src_binding);
2807 else if (!dst->buffer_object && src->buffer_object)
2809 context_bind_bo(context, src_binding, src->buffer_object);
2810 GL_EXTCALL(glGetBufferSubData(src_binding, (GLintptr)src->addr, size, dst->addr));
2811 checkGLcall("buffer download");
2813 else if (dst->buffer_object && !src->buffer_object)
2815 context_bind_bo(context, dst_binding, dst->buffer_object);
2816 GL_EXTCALL(glBufferSubData(dst_binding, (GLintptr)dst->addr, size, src->addr));
2817 checkGLcall("buffer upload");
2819 else
2821 memcpy(dst->addr, src->addr, size);
2825 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2827 if (context->render_offscreen == offscreen)
2828 return;
2830 context_invalidate_state(context, STATE_VIEWPORT);
2831 context_invalidate_state(context, STATE_SCISSORRECT);
2832 if (!context->gl_info->supported[ARB_CLIP_CONTROL])
2834 context_invalidate_state(context, STATE_FRONTFACE);
2835 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2836 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2838 context_invalidate_state(context, STATE_SHADER(WINED3D_SHADER_TYPE_DOMAIN));
2839 if (context->gl_info->supported[ARB_FRAGMENT_COORD_CONVENTIONS])
2840 context_invalidate_state(context, STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL));
2841 context->render_offscreen = offscreen;
2844 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2845 const struct wined3d_format *required)
2847 if (existing == required)
2848 return TRUE;
2849 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2850 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2851 return FALSE;
2852 if (existing->depth_size < required->depth_size)
2853 return FALSE;
2854 /* If stencil bits are used the exact amount is required - otherwise
2855 * wrapping won't work correctly. */
2856 if (required->stencil_size && required->stencil_size != existing->stencil_size)
2857 return FALSE;
2858 return TRUE;
2861 /* Context activation is done by the caller. */
2862 static void context_validate_onscreen_formats(struct wined3d_context *context,
2863 const struct wined3d_rendertarget_view *depth_stencil)
2865 /* Onscreen surfaces are always in a swapchain */
2866 struct wined3d_swapchain *swapchain = context->current_rt.texture->swapchain;
2868 if (context->render_offscreen || !depth_stencil) return;
2869 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2871 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2872 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2873 * format. */
2874 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2876 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2877 if (!(wined3d_texture_load_location(context->current_rt.texture, context->current_rt.sub_resource_idx,
2878 context, WINED3D_LOCATION_TEXTURE_RGB)))
2879 ERR("Failed to load location.\n");
2880 swapchain->render_to_fbo = TRUE;
2881 swapchain_update_draw_bindings(swapchain);
2882 context_set_render_offscreen(context, TRUE);
2885 GLenum context_get_offscreen_gl_buffer(const struct wined3d_context *context)
2887 switch (wined3d_settings.offscreen_rendering_mode)
2889 case ORM_FBO:
2890 return GL_COLOR_ATTACHMENT0;
2892 case ORM_BACKBUFFER:
2893 return context->aux_buffers > 0 ? GL_AUX0 : GL_BACK;
2895 default:
2896 FIXME("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
2897 return GL_BACK;
2901 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_context *context, struct wined3d_texture *rt)
2903 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2904 return 0;
2905 else if (rt->swapchain)
2906 return context_generate_rt_mask_from_resource(&rt->resource);
2907 else
2908 return context_generate_rt_mask(context_get_offscreen_gl_buffer(context));
2911 /* Context activation is done by the caller. */
2912 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2914 struct wined3d_texture *rt = context->current_rt.texture;
2915 struct wined3d_surface *surface;
2916 DWORD rt_mask, *cur_mask;
2918 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2920 context_validate_onscreen_formats(context, NULL);
2922 if (context->render_offscreen)
2924 wined3d_texture_load(rt, context, FALSE);
2926 surface = rt->sub_resources[context->current_rt.sub_resource_idx].u.surface;
2927 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, surface, NULL, rt->resource.draw_binding);
2928 if (rt->resource.format->id != WINED3DFMT_NULL)
2929 rt_mask = 1;
2930 else
2931 rt_mask = 0;
2933 else
2935 context->current_fbo = NULL;
2936 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2937 rt_mask = context_generate_rt_mask_from_resource(&rt->resource);
2940 else
2942 rt_mask = context_generate_rt_mask_no_fbo(context, rt);
2945 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2947 if (rt_mask != *cur_mask)
2949 context_apply_draw_buffers(context, rt_mask);
2950 *cur_mask = rt_mask;
2953 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2955 context_check_fbo_status(context, GL_FRAMEBUFFER);
2958 SetupForBlit(device, context);
2959 context_invalidate_state(context, STATE_FRAMEBUFFER);
2962 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2963 const struct wined3d_rendertarget_view *ds)
2965 unsigned int i;
2967 if (ds) return TRUE;
2969 for (i = 0; i < rt_count; ++i)
2971 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2972 return TRUE;
2975 WARN("Invalid render target config, need at least one attachment.\n");
2976 return FALSE;
2979 /* Context activation is done by the caller. */
2980 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_state *state,
2981 UINT rt_count, const struct wined3d_fb_state *fb)
2983 struct wined3d_rendertarget_view **rts = fb->render_targets;
2984 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2985 const struct wined3d_gl_info *gl_info = context->gl_info;
2986 DWORD rt_mask = 0, *cur_mask;
2987 unsigned int i;
2989 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != state->fb
2990 || rt_count != gl_info->limits.buffers)
2992 if (!context_validate_rt_config(rt_count, rts, dsv))
2993 return FALSE;
2995 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2997 context_validate_onscreen_formats(context, dsv);
2999 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
3001 memset(context->blit_targets, 0, gl_info->limits.buffers * sizeof(*context->blit_targets));
3002 for (i = 0; i < rt_count; ++i)
3004 if (rts[i])
3006 context->blit_targets[i].gl_view = rts[i]->gl_view;
3007 context->blit_targets[i].resource = rts[i]->resource;
3008 context->blit_targets[i].sub_resource_idx = rts[i]->sub_resource_idx;
3009 context->blit_targets[i].layer_count = rts[i]->layer_count;
3011 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
3012 rt_mask |= (1u << i);
3014 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
3015 wined3d_rendertarget_view_get_surface(dsv),
3016 rt_count ? rts[0]->resource->draw_binding : 0,
3017 dsv ? dsv->resource->draw_binding : 0);
3019 else
3021 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
3022 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
3023 rt_mask = context_generate_rt_mask_from_resource(rts[0]->resource);
3026 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
3027 * next draw. Otherwise we could mark the framebuffer state clean here, once the
3028 * state management allows this */
3029 context_invalidate_state(context, STATE_FRAMEBUFFER);
3031 else
3033 rt_mask = context_generate_rt_mask_no_fbo(context,
3034 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
3037 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
3038 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
3040 for (i = 0; i < rt_count; ++i)
3042 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
3043 rt_mask |= (1u << i);
3046 else
3048 rt_mask = context_generate_rt_mask_no_fbo(context,
3049 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
3052 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3054 if (rt_mask != *cur_mask)
3056 context_apply_draw_buffers(context, rt_mask);
3057 *cur_mask = rt_mask;
3058 context_invalidate_state(context, STATE_FRAMEBUFFER);
3061 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3063 context_check_fbo_status(context, GL_FRAMEBUFFER);
3066 context->last_was_blit = FALSE;
3068 /* Blending and clearing should be orthogonal, but tests on the nvidia
3069 * driver show that disabling blending when clearing improves the clearing
3070 * performance incredibly. */
3071 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
3072 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
3073 if (rt_count && gl_info->supported[ARB_FRAMEBUFFER_SRGB])
3075 if (needs_srgb_write(context, state, fb))
3076 gl_info->gl_ops.gl.p_glEnable(GL_FRAMEBUFFER_SRGB);
3077 else
3078 gl_info->gl_ops.gl.p_glDisable(GL_FRAMEBUFFER_SRGB);
3079 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3081 checkGLcall("setting up state for clear");
3083 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3084 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
3085 context_invalidate_state(context, STATE_SCISSORRECT);
3087 return TRUE;
3090 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_state *state)
3092 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
3093 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
3094 DWORD rt_mask, rt_mask_bits;
3095 unsigned int i;
3097 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
3098 return context_generate_rt_mask_no_fbo(context, wined3d_rendertarget_view_get_surface(rts[0])->container);
3099 else if (!context->render_offscreen)
3100 return context_generate_rt_mask_from_resource(rts[0]->resource);
3102 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
3103 rt_mask &= context->d3d_info->valid_rt_mask;
3104 rt_mask_bits = rt_mask;
3105 i = 0;
3106 while (rt_mask_bits)
3108 rt_mask_bits &= ~(1u << i);
3109 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
3110 rt_mask &= ~(1u << i);
3112 i++;
3115 return rt_mask;
3118 /* Context activation is done by the caller. */
3119 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
3121 DWORD rt_mask = find_draw_buffers_mask(context, state);
3122 const struct wined3d_fb_state *fb = state->fb;
3123 DWORD *cur_mask;
3125 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3127 if (!context->render_offscreen)
3129 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
3130 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
3132 else
3134 unsigned int i;
3136 memset(context->blit_targets, 0, context->gl_info->limits.buffers * sizeof (*context->blit_targets));
3137 for (i = 0; i < context->gl_info->limits.buffers; ++i)
3139 if (fb->render_targets[i])
3141 context->blit_targets[i].gl_view = fb->render_targets[i]->gl_view;
3142 context->blit_targets[i].resource = fb->render_targets[i]->resource;
3143 context->blit_targets[i].sub_resource_idx = fb->render_targets[i]->sub_resource_idx;
3144 context->blit_targets[i].layer_count = fb->render_targets[i]->layer_count;
3147 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
3148 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
3149 fb->render_targets[0] ? fb->render_targets[0]->resource->draw_binding : 0,
3150 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
3154 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3155 if (rt_mask != *cur_mask)
3157 context_apply_draw_buffers(context, rt_mask);
3158 *cur_mask = rt_mask;
3160 context->constant_update_mask |= WINED3D_SHADER_CONST_PS_Y_CORR;
3163 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
3165 DWORD i = context->rev_tex_unit_map[unit];
3166 DWORD j = context->tex_unit_map[stage];
3168 TRACE("Mapping stage %u to unit %u.\n", stage, unit);
3169 context->tex_unit_map[stage] = unit;
3170 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
3171 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
3173 context->rev_tex_unit_map[unit] = stage;
3174 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
3175 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
3178 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
3180 DWORD i;
3182 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
3183 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
3186 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
3187 const struct wined3d_state *state)
3189 UINT i, start, end;
3191 context->fixed_function_usage_map = 0;
3192 for (i = 0; i < MAX_TEXTURES; ++i)
3194 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
3195 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
3196 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
3197 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
3198 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
3199 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
3200 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
3201 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
3203 /* Not used, and disable higher stages. */
3204 if (color_op == WINED3D_TOP_DISABLE)
3205 break;
3207 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
3208 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
3209 || ((color_arg3 == WINED3DTA_TEXTURE)
3210 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
3211 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
3212 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
3213 || ((alpha_arg3 == WINED3DTA_TEXTURE)
3214 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
3215 context->fixed_function_usage_map |= (1u << i);
3217 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
3218 && i < MAX_TEXTURES - 1)
3219 context->fixed_function_usage_map |= (1u << (i + 1));
3222 if (i < context->lowest_disabled_stage)
3224 start = i;
3225 end = context->lowest_disabled_stage;
3227 else
3229 start = context->lowest_disabled_stage;
3230 end = i;
3233 context->lowest_disabled_stage = i;
3234 for (i = start + 1; i < end; ++i)
3236 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3240 static void context_map_fixed_function_samplers(struct wined3d_context *context,
3241 const struct wined3d_state *state)
3243 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3244 unsigned int i, tex;
3245 WORD ffu_map;
3247 ffu_map = context->fixed_function_usage_map;
3249 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
3250 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
3252 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3254 if (!(ffu_map & 1))
3255 continue;
3257 if (context->tex_unit_map[i] != i)
3259 context_map_stage(context, i, i);
3260 context_invalidate_state(context, STATE_SAMPLER(i));
3261 context_invalidate_texture_stage(context, i);
3264 return;
3267 /* Now work out the mapping */
3268 tex = 0;
3269 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3271 if (!(ffu_map & 1))
3272 continue;
3274 if (context->tex_unit_map[i] != tex)
3276 context_map_stage(context, i, tex);
3277 context_invalidate_state(context, STATE_SAMPLER(i));
3278 context_invalidate_texture_stage(context, i);
3281 ++tex;
3285 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
3287 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3288 const struct wined3d_shader_resource_info *resource_info =
3289 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
3290 unsigned int i;
3292 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3294 if (resource_info[i].type && context->tex_unit_map[i] != i)
3296 context_map_stage(context, i, i);
3297 context_invalidate_state(context, STATE_SAMPLER(i));
3298 if (i < d3d_info->limits.ffp_blend_stages)
3299 context_invalidate_texture_stage(context, i);
3304 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
3305 const struct wined3d_shader_resource_info *ps_resource_info, DWORD unit)
3307 DWORD current_mapping = context->rev_tex_unit_map[unit];
3309 /* Not currently used */
3310 if (current_mapping == WINED3D_UNMAPPED_STAGE)
3311 return TRUE;
3313 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
3315 /* Used by a fragment sampler */
3317 if (!ps_resource_info)
3319 /* No pixel shader, check fixed function */
3320 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1u << current_mapping));
3323 /* Pixel shader, check the shader's sampler map */
3324 return !ps_resource_info[current_mapping].type;
3327 return TRUE;
3330 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
3332 const struct wined3d_shader_resource_info *vs_resource_info =
3333 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
3334 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
3335 const struct wined3d_gl_info *gl_info = context->gl_info;
3336 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.graphics_samplers) - 1;
3337 int i;
3339 /* Note that we only care if a resource is used or not, not the
3340 * resource's specific type. Otherwise we'd need to call
3341 * shader_update_samplers() here for 1.x pixelshaders. */
3342 if (ps)
3343 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
3345 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3347 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
3348 if (vs_resource_info[i].type)
3350 while (start >= 0)
3352 if (context_unit_free_for_vs(context, ps_resource_info, start))
3354 if (context->tex_unit_map[vsampler_idx] != start)
3356 context_map_stage(context, vsampler_idx, start);
3357 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
3360 --start;
3361 break;
3364 --start;
3366 if (context->tex_unit_map[vsampler_idx] == WINED3D_UNMAPPED_STAGE)
3367 WARN("Couldn't find a free texture unit for vertex sampler %u.\n", i);
3372 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
3374 const struct wined3d_gl_info *gl_info = context->gl_info;
3375 BOOL vs = use_vs(state);
3376 BOOL ps = use_ps(state);
3378 if (!ps)
3379 context_update_fixed_function_usage_map(context, state);
3381 /* Try to go for a 1:1 mapping of the samplers when possible. Pixel shaders
3382 * need a 1:1 map at the moment.
3383 * When the mapping of a stage is changed, sampler and ALL texture stage
3384 * states have to be reset. */
3386 if (gl_info->limits.graphics_samplers >= MAX_COMBINED_SAMPLERS)
3387 return;
3389 if (ps)
3390 context_map_psamplers(context, state);
3391 else
3392 context_map_fixed_function_samplers(context, state);
3394 if (vs)
3395 context_map_vsamplers(context, ps, state);
3398 /* Context activation is done by the caller. */
3399 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
3401 DWORD rt_mask, *cur_mask;
3403 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
3405 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3406 rt_mask = find_draw_buffers_mask(context, state);
3407 if (rt_mask != *cur_mask)
3409 context_apply_draw_buffers(context, rt_mask);
3410 *cur_mask = rt_mask;
3414 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
3416 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
3417 *regnum = WINED3D_FFP_POSITION;
3418 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
3419 *regnum = WINED3D_FFP_BLENDWEIGHT;
3420 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
3421 *regnum = WINED3D_FFP_BLENDINDICES;
3422 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
3423 *regnum = WINED3D_FFP_NORMAL;
3424 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
3425 *regnum = WINED3D_FFP_PSIZE;
3426 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
3427 *regnum = WINED3D_FFP_DIFFUSE;
3428 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
3429 *regnum = WINED3D_FFP_SPECULAR;
3430 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
3431 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
3432 else
3434 WARN("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
3435 *regnum = ~0u;
3436 return FALSE;
3439 return TRUE;
3442 /* Context activation is done by the caller. */
3443 void wined3d_stream_info_from_declaration(struct wined3d_stream_info *stream_info,
3444 const struct wined3d_state *state, const struct wined3d_gl_info *gl_info,
3445 const struct wined3d_d3d_info *d3d_info)
3447 /* We need to deal with frequency data! */
3448 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
3449 BOOL generic_attributes = d3d_info->ffp_generic_attributes;
3450 BOOL use_vshader = use_vs(state);
3451 unsigned int i;
3453 stream_info->use_map = 0;
3454 stream_info->swizzle_map = 0;
3455 stream_info->position_transformed = 0;
3457 if (!declaration)
3458 return;
3460 stream_info->position_transformed = declaration->position_transformed;
3462 /* Translate the declaration into strided data. */
3463 for (i = 0; i < declaration->element_count; ++i)
3465 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
3466 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
3467 BOOL stride_used;
3468 unsigned int idx;
3470 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
3471 element, i + 1, declaration->element_count);
3473 if (!stream->buffer)
3474 continue;
3476 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
3478 if (use_vshader)
3480 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
3482 stride_used = FALSE;
3484 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
3486 /* TODO: Assuming vertexdeclarations are usually used with the
3487 * same or a similar shader, it might be worth it to store the
3488 * last used output slot and try that one first. */
3489 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
3490 element->usage, element->usage_idx, &idx);
3492 else
3494 idx = element->output_slot;
3495 stride_used = TRUE;
3498 else
3500 if (!generic_attributes && !element->ffp_valid)
3502 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
3503 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
3504 stride_used = FALSE;
3506 else
3508 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
3512 if (stride_used)
3514 TRACE("Load %s array %u [usage %s, usage_idx %u, "
3515 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
3516 use_vshader ? "shader": "fixed function", idx,
3517 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
3518 element->offset, stream->stride, debug_d3dformat(element->format->id),
3519 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
3521 stream_info->elements[idx].format = element->format;
3522 stream_info->elements[idx].data.buffer_object = 0;
3523 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
3524 stream_info->elements[idx].stride = stream->stride;
3525 stream_info->elements[idx].stream_idx = element->input_slot;
3526 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
3528 stream_info->elements[idx].divisor = 1;
3530 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
3532 stream_info->elements[idx].divisor = element->instance_data_step_rate;
3533 if (!element->instance_data_step_rate)
3534 FIXME("Instance step rate 0 not implemented.\n");
3536 else
3538 stream_info->elements[idx].divisor = 0;
3541 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3542 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
3544 stream_info->swizzle_map |= 1u << idx;
3546 stream_info->use_map |= 1u << idx;
3551 /* Context activation is done by the caller. */
3552 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
3554 struct wined3d_stream_info *stream_info = &context->stream_info;
3555 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3556 const struct wined3d_gl_info *gl_info = context->gl_info;
3557 DWORD prev_all_vbo = stream_info->all_vbo;
3558 unsigned int i;
3559 WORD map;
3561 wined3d_stream_info_from_declaration(stream_info, state, gl_info, d3d_info);
3563 stream_info->all_vbo = 1;
3564 context->buffer_fence_count = 0;
3565 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
3567 struct wined3d_stream_info_element *element;
3568 struct wined3d_bo_address data;
3569 struct wined3d_buffer *buffer;
3571 if (!(map & 1))
3572 continue;
3574 element = &stream_info->elements[i];
3575 buffer = state->streams[element->stream_idx].buffer;
3577 /* We can't use VBOs if the base vertex index is negative. OpenGL
3578 * doesn't accept negative offsets (or rather offsets bigger than the
3579 * VBO, because the pointer is unsigned), so use system memory
3580 * sources. In most sane cases the pointer - offset will still be > 0,
3581 * otherwise it will wrap around to some big value. Hope that with the
3582 * indices the driver wraps it back internally. If not,
3583 * draw_primitive_immediate_mode() is needed, including a vertex buffer
3584 * path. */
3585 if (state->load_base_vertex_index < 0)
3587 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
3588 state->load_base_vertex_index);
3589 element->data.buffer_object = 0;
3590 element->data.addr += (ULONG_PTR)wined3d_buffer_load_sysmem(buffer, context);
3591 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
3592 FIXME("System memory vertex data load offset is negative!\n");
3594 else
3596 wined3d_buffer_load(buffer, context, state);
3597 wined3d_buffer_get_memory(buffer, &data, buffer->locations);
3598 element->data.buffer_object = data.buffer_object;
3599 element->data.addr += (ULONG_PTR)data.addr;
3602 if (!element->data.buffer_object)
3603 stream_info->all_vbo = 0;
3605 if (buffer->fence)
3606 context->buffer_fences[context->buffer_fence_count++] = buffer->fence;
3608 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
3611 if (prev_all_vbo != stream_info->all_vbo)
3612 context_invalidate_state(context, STATE_INDEXBUFFER);
3614 context->use_immediate_mode_draw = FALSE;
3616 if (stream_info->all_vbo)
3617 return;
3619 if (use_vs(state))
3621 if (state->vertex_declaration->half_float_conv_needed)
3623 TRACE("Using immediate mode draw with vertex shaders for FLOAT16 conversion.\n");
3624 context->use_immediate_mode_draw = TRUE;
3627 else
3629 WORD slow_mask = -!d3d_info->ffp_generic_attributes & (1u << WINED3D_FFP_PSIZE);
3630 slow_mask |= -(!gl_info->supported[ARB_VERTEX_ARRAY_BGRA] && !d3d_info->ffp_generic_attributes)
3631 & ((1u << WINED3D_FFP_DIFFUSE) | (1u << WINED3D_FFP_SPECULAR) | (1u << WINED3D_FFP_BLENDWEIGHT));
3633 if ((stream_info->position_transformed && !d3d_info->xyzrhw)
3634 || (stream_info->use_map & slow_mask))
3635 context->use_immediate_mode_draw = TRUE;
3639 /* Context activation is done by the caller. */
3640 static void context_preload_texture(struct wined3d_context *context,
3641 const struct wined3d_state *state, unsigned int idx)
3643 struct wined3d_texture *texture;
3645 if (!(texture = state->textures[idx]))
3646 return;
3648 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3651 /* Context activation is done by the caller. */
3652 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3654 unsigned int i;
3656 if (use_vs(state))
3658 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3660 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3661 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3665 if (use_ps(state))
3667 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3669 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3670 context_preload_texture(context, state, i);
3673 else
3675 WORD ffu_map = context->fixed_function_usage_map;
3677 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3679 if (ffu_map & 1)
3680 context_preload_texture(context, state, i);
3685 static void context_load_shader_resources(struct wined3d_context *context, const struct wined3d_state *state,
3686 unsigned int shader_mask)
3688 struct wined3d_shader_sampler_map_entry *entry;
3689 struct wined3d_shader_resource_view *view;
3690 struct wined3d_shader *shader;
3691 unsigned int i, j;
3693 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3695 if (!(shader_mask & (1u << i)))
3696 continue;
3698 if (!(shader = state->shader[i]))
3699 continue;
3701 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3703 if (state->cb[i][j])
3704 wined3d_buffer_load(state->cb[i][j], context, state);
3707 for (j = 0; j < shader->reg_maps.sampler_map.count; ++j)
3709 entry = &shader->reg_maps.sampler_map.entries[j];
3711 if (!(view = state->shader_resource_view[i][entry->resource_idx]))
3712 continue;
3714 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3715 wined3d_buffer_load(buffer_from_resource(view->resource), context, state);
3716 else
3717 wined3d_texture_load(texture_from_resource(view->resource), context, FALSE);
3722 static void context_bind_shader_resources(struct wined3d_context *context,
3723 const struct wined3d_state *state, enum wined3d_shader_type shader_type)
3725 unsigned int bind_idx, shader_sampler_count, base, count, i;
3726 const struct wined3d_device *device = context->device;
3727 struct wined3d_shader_sampler_map_entry *entry;
3728 struct wined3d_shader_resource_view *view;
3729 const struct wined3d_shader *shader;
3730 struct wined3d_sampler *sampler;
3731 const DWORD *tex_unit_map;
3733 if (!(shader = state->shader[shader_type]))
3734 return;
3736 tex_unit_map = context_get_tex_unit_mapping(context,
3737 &shader->reg_maps.shader_version, &base, &count);
3739 shader_sampler_count = shader->reg_maps.sampler_map.count;
3740 if (shader_sampler_count > count)
3741 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3742 shader, shader_sampler_count, count);
3743 count = min(shader_sampler_count, count);
3745 for (i = 0; i < count; ++i)
3747 entry = &shader->reg_maps.sampler_map.entries[i];
3748 bind_idx = base + entry->bind_idx;
3749 if (tex_unit_map)
3750 bind_idx = tex_unit_map[bind_idx];
3752 if (!(view = state->shader_resource_view[shader_type][entry->resource_idx]))
3754 WARN("No resource view bound at index %u, %u.\n", shader_type, entry->resource_idx);
3755 continue;
3758 if (entry->sampler_idx == WINED3D_SAMPLER_DEFAULT)
3759 sampler = device->default_sampler;
3760 else if (!(sampler = state->sampler[shader_type][entry->sampler_idx]))
3761 sampler = device->null_sampler;
3762 wined3d_shader_resource_view_bind(view, bind_idx, sampler, context);
3766 static void context_load_unordered_access_resources(struct wined3d_context *context,
3767 const struct wined3d_shader *shader, struct wined3d_unordered_access_view * const *views)
3769 struct wined3d_unordered_access_view *view;
3770 struct wined3d_texture *texture;
3771 struct wined3d_buffer *buffer;
3772 unsigned int i;
3774 context->uses_uavs = 0;
3776 if (!shader)
3777 return;
3779 for (i = 0; i < MAX_UNORDERED_ACCESS_VIEWS; ++i)
3781 if (!(view = views[i]))
3782 continue;
3784 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3786 buffer = buffer_from_resource(view->resource);
3787 wined3d_buffer_load_location(buffer, context, WINED3D_LOCATION_BUFFER);
3788 wined3d_unordered_access_view_invalidate_location(view, ~WINED3D_LOCATION_BUFFER);
3790 else
3792 texture = texture_from_resource(view->resource);
3793 wined3d_texture_load(texture, context, FALSE);
3794 wined3d_unordered_access_view_invalidate_location(view, ~WINED3D_LOCATION_TEXTURE_RGB);
3797 context->uses_uavs = 1;
3801 static void context_bind_unordered_access_views(struct wined3d_context *context,
3802 const struct wined3d_shader *shader, struct wined3d_unordered_access_view * const *views)
3804 const struct wined3d_gl_info *gl_info = context->gl_info;
3805 struct wined3d_unordered_access_view *view;
3806 GLuint texture_name;
3807 unsigned int i;
3808 GLint level;
3810 if (!shader)
3811 return;
3813 for (i = 0; i < MAX_UNORDERED_ACCESS_VIEWS; ++i)
3815 if (!(view = views[i]))
3817 if (shader->reg_maps.uav_resource_info[i].type)
3818 WARN("No unordered access view bound at index %u.\n", i);
3819 GL_EXTCALL(glBindImageTexture(i, 0, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8));
3820 continue;
3823 if (view->gl_view.name)
3825 texture_name = view->gl_view.name;
3826 level = 0;
3828 else if (view->resource->type != WINED3D_RTYPE_BUFFER)
3830 struct wined3d_texture *texture = texture_from_resource(view->resource);
3831 texture_name = wined3d_texture_get_texture_name(texture, context, FALSE);
3832 level = view->desc.u.texture.level_idx;
3834 else
3836 FIXME("Unsupported buffer unordered access view.\n");
3837 GL_EXTCALL(glBindImageTexture(i, 0, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8));
3838 continue;
3841 GL_EXTCALL(glBindImageTexture(i, texture_name, level, GL_TRUE, 0, GL_READ_WRITE,
3842 view->format->glInternal));
3844 if (view->counter_bo)
3845 GL_EXTCALL(glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, i, view->counter_bo));
3847 checkGLcall("Bind unordered access views");
3850 static void context_load_stream_output_buffers(struct wined3d_context *context,
3851 const struct wined3d_state *state)
3853 unsigned int i;
3855 for (i = 0; i < ARRAY_SIZE(state->stream_output); ++i)
3857 struct wined3d_buffer *buffer;
3858 if (!(buffer = state->stream_output[i].buffer))
3859 continue;
3861 wined3d_buffer_load(buffer, context, state);
3862 wined3d_buffer_invalidate_location(buffer, ~WINED3D_LOCATION_BUFFER);
3866 /* Context activation is done by the caller. */
3867 BOOL context_apply_draw_state(struct wined3d_context *context,
3868 const struct wined3d_device *device, const struct wined3d_state *state)
3870 const struct StateEntry *state_table = context->state_table;
3871 const struct wined3d_gl_info *gl_info = context->gl_info;
3872 const struct wined3d_fb_state *fb = state->fb;
3873 unsigned int i;
3874 WORD map;
3876 if (!context_validate_rt_config(gl_info->limits.buffers, fb->render_targets, fb->depth_stencil))
3877 return FALSE;
3879 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3881 context_validate_onscreen_formats(context, fb->depth_stencil);
3884 /* Preload resources before FBO setup. Texture preload in particular may
3885 * result in changes to the current FBO, due to using e.g. FBO blits for
3886 * updating a resource location. */
3887 context_update_tex_unit_map(context, state);
3888 context_preload_textures(context, state);
3889 context_load_shader_resources(context, state, ~(1u << WINED3D_SHADER_TYPE_COMPUTE));
3890 context_load_unordered_access_resources(context, state->shader[WINED3D_SHADER_TYPE_PIXEL],
3891 state->unordered_access_view[WINED3D_PIPELINE_GRAPHICS]);
3892 context_load_stream_output_buffers(context, state);
3893 /* TODO: Right now the dependency on the vertex shader is necessary
3894 * since wined3d_stream_info_from_declaration() depends on the reg_maps of
3895 * the current VS but maybe it's possible to relax the coupling in some
3896 * situations at least. */
3897 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3898 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3900 context_update_stream_info(context, state);
3902 else
3904 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3906 if (map & 1)
3907 wined3d_buffer_load(state->streams[context->stream_info.elements[i].stream_idx].buffer,
3908 context, state);
3910 /* Loading the buffers above may have invalidated the stream info. */
3911 if (isStateDirty(context, STATE_STREAMSRC))
3912 context_update_stream_info(context, state);
3914 if (state->index_buffer)
3916 if (context->stream_info.all_vbo)
3917 wined3d_buffer_load(state->index_buffer, context, state);
3918 else
3919 wined3d_buffer_load_sysmem(state->index_buffer, context);
3922 for (i = 0; i < context->numDirtyEntries; ++i)
3924 DWORD rep = context->dirtyArray[i];
3925 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3926 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3927 context->isStateDirty[idx] &= ~(1u << shift);
3928 state_table[rep].apply(context, state, rep);
3931 if (context->shader_update_mask & ~(1u << WINED3D_SHADER_TYPE_COMPUTE))
3933 device->shader_backend->shader_select(device->shader_priv, context, state);
3934 context->shader_update_mask &= 1u << WINED3D_SHADER_TYPE_COMPUTE;
3937 if (context->constant_update_mask)
3939 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3940 context->constant_update_mask = 0;
3943 if (context->update_shader_resource_bindings)
3945 for (i = 0; i < WINED3D_SHADER_TYPE_GRAPHICS_COUNT; ++i)
3946 context_bind_shader_resources(context, state, i);
3947 context->update_shader_resource_bindings = 0;
3948 if (gl_info->limits.combined_samplers == gl_info->limits.graphics_samplers)
3949 context->update_compute_shader_resource_bindings = 1;
3952 if (context->update_unordered_access_view_bindings)
3954 context_bind_unordered_access_views(context,
3955 state->shader[WINED3D_SHADER_TYPE_PIXEL],
3956 state->unordered_access_view[WINED3D_PIPELINE_GRAPHICS]);
3957 context->update_unordered_access_view_bindings = 0;
3958 context->update_compute_unordered_access_view_bindings = 1;
3961 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3963 context_check_fbo_status(context, GL_FRAMEBUFFER);
3966 context->numDirtyEntries = 0; /* This makes the whole list clean */
3967 context->last_was_blit = FALSE;
3969 return TRUE;
3972 void context_apply_compute_state(struct wined3d_context *context,
3973 const struct wined3d_device *device, const struct wined3d_state *state)
3975 const struct StateEntry *state_table = context->state_table;
3976 const struct wined3d_gl_info *gl_info = context->gl_info;
3977 unsigned int state_id, i, j;
3979 context_load_shader_resources(context, state, 1u << WINED3D_SHADER_TYPE_COMPUTE);
3980 context_load_unordered_access_resources(context, state->shader[WINED3D_SHADER_TYPE_COMPUTE],
3981 state->unordered_access_view[WINED3D_PIPELINE_COMPUTE]);
3983 for (i = 0, state_id = STATE_COMPUTE_OFFSET; i < ARRAY_SIZE(context->dirty_compute_states); ++i)
3985 for (j = 0; j < sizeof(*context->dirty_compute_states) * CHAR_BIT; ++j, ++state_id)
3987 if (context->dirty_compute_states[i] & (1u << j))
3988 state_table[state_id].apply(context, state, state_id);
3991 memset(context->dirty_compute_states, 0, sizeof(*context->dirty_compute_states));
3993 if (context->shader_update_mask & (1u << WINED3D_SHADER_TYPE_COMPUTE))
3995 device->shader_backend->shader_select_compute(device->shader_priv, context, state);
3996 context->shader_update_mask &= ~(1u << WINED3D_SHADER_TYPE_COMPUTE);
3999 if (context->update_compute_shader_resource_bindings)
4001 context_bind_shader_resources(context, state, WINED3D_SHADER_TYPE_COMPUTE);
4002 context->update_compute_shader_resource_bindings = 0;
4003 if (gl_info->limits.combined_samplers == gl_info->limits.graphics_samplers)
4004 context->update_shader_resource_bindings = 1;
4007 if (context->update_compute_unordered_access_view_bindings)
4009 context_bind_unordered_access_views(context,
4010 state->shader[WINED3D_SHADER_TYPE_COMPUTE],
4011 state->unordered_access_view[WINED3D_PIPELINE_COMPUTE]);
4012 context->update_compute_unordered_access_view_bindings = 0;
4013 context->update_unordered_access_view_bindings = 1;
4016 /* Updates to currently bound render targets aren't necessarily coherent
4017 * between the graphics and compute pipelines. Unbind any currently bound
4018 * FBO here to ensure preceding updates to its attachments by the graphics
4019 * pipeline are visible to the compute pipeline.
4021 * Without this, the bloom effect in Nier:Automata is too bright on the
4022 * Mesa radeonsi driver, and presumably on other Mesa based drivers. */
4023 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
4024 context_invalidate_state(context, STATE_FRAMEBUFFER);
4026 context->last_was_blit = FALSE;
4029 void context_end_transform_feedback(struct wined3d_context *context)
4031 const struct wined3d_gl_info *gl_info = context->gl_info;
4032 if (context->transform_feedback_active)
4034 GL_EXTCALL(glEndTransformFeedback());
4035 checkGLcall("glEndTransformFeedback");
4036 context->transform_feedback_active = 0;
4037 context->transform_feedback_paused = 0;
4041 static void context_setup_target(struct wined3d_context *context,
4042 struct wined3d_texture *texture, unsigned int sub_resource_idx)
4044 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
4046 render_offscreen = wined3d_resource_is_offscreen(&texture->resource);
4047 if (context->current_rt.texture == texture
4048 && context->current_rt.sub_resource_idx == sub_resource_idx
4049 && render_offscreen == old_render_offscreen)
4050 return;
4052 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
4053 * the alpha blend state changes with different render target formats. */
4054 if (!context->current_rt.texture)
4056 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
4058 else
4060 const struct wined3d_format *old = context->current_rt.texture->resource.format;
4061 const struct wined3d_format *new = texture->resource.format;
4063 if (old->id != new->id)
4065 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
4066 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
4067 || !(texture->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
4068 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
4070 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
4071 if ((context->current_rt.texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
4072 != (texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
4073 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
4076 /* When switching away from an offscreen render target, and we're not
4077 * using FBOs, we have to read the drawable into the texture. This is
4078 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
4079 * There are some things that need care though. PreLoad needs a GL context,
4080 * and FindContext is called before the context is activated. It also
4081 * has to be called with the old rendertarget active, otherwise a
4082 * wrong drawable is read. */
4083 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
4084 && old_render_offscreen && (context->current_rt.texture != texture
4085 || context->current_rt.sub_resource_idx != sub_resource_idx))
4087 unsigned int prev_sub_resource_idx = context->current_rt.sub_resource_idx;
4088 struct wined3d_texture *prev_texture = context->current_rt.texture;
4090 /* Read the back buffer of the old drawable into the destination texture. */
4091 if (prev_texture->texture_srgb.name)
4092 wined3d_texture_load(prev_texture, context, TRUE);
4093 wined3d_texture_load(prev_texture, context, FALSE);
4094 wined3d_texture_invalidate_location(prev_texture, prev_sub_resource_idx, WINED3D_LOCATION_DRAWABLE);
4098 context->current_rt.texture = texture;
4099 context->current_rt.sub_resource_idx = sub_resource_idx;
4100 context_set_render_offscreen(context, render_offscreen);
4103 struct wined3d_context *context_acquire(const struct wined3d_device *device,
4104 struct wined3d_texture *texture, unsigned int sub_resource_idx)
4106 struct wined3d_context *current_context = context_get_current();
4107 struct wined3d_context *context;
4108 BOOL swapchain_texture;
4110 TRACE("device %p, texture %p, sub_resource_idx %u.\n", device, texture, sub_resource_idx);
4112 wined3d_from_cs(device->cs);
4114 if (current_context && current_context->destroyed)
4115 current_context = NULL;
4117 swapchain_texture = texture && texture->swapchain;
4118 if (!texture)
4120 if (current_context
4121 && current_context->current_rt.texture
4122 && current_context->device == device)
4124 texture = current_context->current_rt.texture;
4125 sub_resource_idx = current_context->current_rt.sub_resource_idx;
4127 else
4129 struct wined3d_swapchain *swapchain = device->swapchains[0];
4131 if (swapchain->back_buffers)
4132 texture = swapchain->back_buffers[0];
4133 else
4134 texture = swapchain->front_buffer;
4135 sub_resource_idx = 0;
4139 if (current_context && current_context->current_rt.texture == texture)
4141 context = current_context;
4143 else if (swapchain_texture)
4145 TRACE("Rendering onscreen.\n");
4147 context = swapchain_get_context(texture->swapchain);
4149 else
4151 TRACE("Rendering offscreen.\n");
4153 /* Stay with the current context if possible. Otherwise use the
4154 * context for the primary swapchain. */
4155 if (current_context && current_context->device == device)
4156 context = current_context;
4157 else
4158 context = swapchain_get_context(device->swapchains[0]);
4161 context_enter(context);
4162 context_update_window(context);
4163 context_setup_target(context, texture, sub_resource_idx);
4164 if (!context->valid)
4165 return context;
4167 if (context != current_context)
4169 if (!context_set_current(context))
4170 ERR("Failed to activate the new context.\n");
4172 else if (context->needs_set)
4174 context_set_gl_context(context);
4177 return context;
4180 struct wined3d_context *context_reacquire(const struct wined3d_device *device,
4181 struct wined3d_context *context)
4183 struct wined3d_context *current_context;
4185 if (!context || context->tid != GetCurrentThreadId())
4186 return NULL;
4188 current_context = context_acquire(device, context->current_rt.texture,
4189 context->current_rt.sub_resource_idx);
4190 if (current_context != context)
4191 ERR("Acquired context %p instead of %p.\n", current_context, context);
4192 return current_context;