wined3d: Don't enumerate sub-resources in wined3d_device_reset().
[wine.git] / dlls / wined3d / context.c
blob6cda974659b96cc39456c9afe4f25318d1b035c4
1 /*
2 * Context and render target management in wined3d
4 * Copyright 2007-2011, 2013 Stefan Dösinger for CodeWeavers
5 * Copyright 2009-2011 Henri Verbeet for CodeWeavers
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "config.h"
23 #include "wine/port.h"
25 #include <stdio.h>
26 #ifdef HAVE_FLOAT_H
27 # include <float.h>
28 #endif
30 #include "wined3d_private.h"
32 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
33 WINE_DECLARE_DEBUG_CHANNEL(d3d_perf);
34 WINE_DECLARE_DEBUG_CHANNEL(d3d_synchronous);
36 #define WINED3D_MAX_FBO_ENTRIES 64
38 static DWORD wined3d_context_tls_idx;
40 /* FBO helper functions */
42 /* Context activation is done by the caller. */
43 static void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint fbo)
45 const struct wined3d_gl_info *gl_info = context->gl_info;
47 switch (target)
49 case GL_READ_FRAMEBUFFER:
50 if (context->fbo_read_binding == fbo) return;
51 context->fbo_read_binding = fbo;
52 break;
54 case GL_DRAW_FRAMEBUFFER:
55 if (context->fbo_draw_binding == fbo) return;
56 context->fbo_draw_binding = fbo;
57 break;
59 case GL_FRAMEBUFFER:
60 if (context->fbo_read_binding == fbo
61 && context->fbo_draw_binding == fbo) return;
62 context->fbo_read_binding = fbo;
63 context->fbo_draw_binding = fbo;
64 break;
66 default:
67 FIXME("Unhandled target %#x.\n", target);
68 break;
71 gl_info->fbo_ops.glBindFramebuffer(target, fbo);
72 checkGLcall("glBindFramebuffer()");
75 /* Context activation is done by the caller. */
76 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info, GLenum target)
78 unsigned int i;
80 for (i = 0; i < gl_info->limits.buffers; ++i)
82 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
83 checkGLcall("glFramebufferTexture2D()");
85 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
86 checkGLcall("glFramebufferTexture2D()");
88 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
89 checkGLcall("glFramebufferTexture2D()");
92 /* Context activation is done by the caller. */
93 static void context_destroy_fbo(struct wined3d_context *context, GLuint fbo)
95 const struct wined3d_gl_info *gl_info = context->gl_info;
97 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
98 context_clean_fbo_attachments(gl_info, GL_FRAMEBUFFER);
99 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
101 gl_info->fbo_ops.glDeleteFramebuffers(1, &fbo);
102 checkGLcall("glDeleteFramebuffers()");
105 static void context_attach_depth_stencil_rb(const struct wined3d_gl_info *gl_info,
106 GLenum fbo_target, DWORD flags, GLuint rb)
108 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
110 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
111 checkGLcall("glFramebufferRenderbuffer()");
114 if (flags & WINED3D_FBO_ENTRY_FLAG_STENCIL)
116 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb);
117 checkGLcall("glFramebufferRenderbuffer()");
121 static void context_attach_gl_texture_fbo(struct wined3d_context *context,
122 GLenum fbo_target, GLenum attachment, const struct wined3d_fbo_resource *resource)
124 const struct wined3d_gl_info *gl_info = context->gl_info;
126 if (!resource)
128 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, attachment, GL_TEXTURE_2D, 0, 0);
129 checkGLcall("glFramebufferTexture2D()");
131 else if (resource->target == GL_TEXTURE_2D_ARRAY)
133 if (!gl_info->fbo_ops.glFramebufferTextureLayer)
135 FIXME("OpenGL implementation doesn't support glFramebufferTextureLayer().\n");
136 return;
139 gl_info->fbo_ops.glFramebufferTextureLayer(fbo_target, attachment,
140 resource->object, resource->level, resource->layer);
141 checkGLcall("glFramebufferTextureLayer()");
143 else
145 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, attachment,
146 resource->target, resource->object, resource->level);
147 checkGLcall("glFramebufferTexture2D()");
151 /* Context activation is done by the caller. */
152 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
153 GLenum fbo_target, const struct wined3d_fbo_resource *resource, BOOL rb_namespace,
154 DWORD flags)
156 const struct wined3d_gl_info *gl_info = context->gl_info;
158 if (resource->object)
160 TRACE("Attach depth stencil %u.\n", resource->object);
162 if (rb_namespace)
164 context_attach_depth_stencil_rb(gl_info, fbo_target,
165 flags, resource->object);
167 else
169 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
170 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, resource);
172 if (flags & WINED3D_FBO_ENTRY_FLAG_STENCIL)
173 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, resource);
176 if (!(flags & WINED3D_FBO_ENTRY_FLAG_DEPTH))
177 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, NULL);
179 if (!(flags & WINED3D_FBO_ENTRY_FLAG_STENCIL))
180 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, NULL);
182 else
184 TRACE("Attach depth stencil 0.\n");
186 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, NULL);
187 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, NULL);
191 /* Context activation is done by the caller. */
192 static void context_attach_surface_fbo(struct wined3d_context *context,
193 GLenum fbo_target, DWORD idx, const struct wined3d_fbo_resource *resource, BOOL rb_namespace)
195 const struct wined3d_gl_info *gl_info = context->gl_info;
197 TRACE("Attach GL object %u to %u.\n", resource->object, idx);
199 if (resource->object)
202 if (rb_namespace)
204 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
205 GL_RENDERBUFFER, resource->object);
206 checkGLcall("glFramebufferRenderbuffer()");
208 else
210 context_attach_gl_texture_fbo(context, fbo_target, GL_COLOR_ATTACHMENT0 + idx, resource);
213 else
215 context_attach_gl_texture_fbo(context, fbo_target, GL_COLOR_ATTACHMENT0 + idx, NULL);
219 static void context_dump_fbo_attachment(const struct wined3d_gl_info *gl_info, GLenum target,
220 GLenum attachment)
222 GLint type, name, samples, width, height, old_texture, level, face, fmt, tex_target;
224 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
225 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &name);
226 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
227 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);
229 if (type == GL_RENDERBUFFER)
231 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, name);
232 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
233 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
234 if (gl_info->limits.samples > 1)
235 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
236 else
237 samples = 1;
238 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &fmt);
239 FIXME(" %s: renderbuffer %d, %dx%d, %d samples, format %#x.\n",
240 debug_fboattachment(attachment), name, width, height, samples, fmt);
242 else if (type == GL_TEXTURE)
244 const char *tex_type_str;
246 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
247 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &level);
248 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
249 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, &face);
251 if (face)
253 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &old_texture);
255 glBindTexture(GL_TEXTURE_CUBE_MAP, name);
256 glGetTexLevelParameteriv(face, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
257 glGetTexLevelParameteriv(face, level, GL_TEXTURE_WIDTH, &width);
258 glGetTexLevelParameteriv(face, level, GL_TEXTURE_HEIGHT, &height);
260 tex_target = GL_TEXTURE_CUBE_MAP;
261 tex_type_str = "cube";
263 else
265 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_texture);
266 while (gl_info->gl_ops.gl.p_glGetError());
268 glBindTexture(GL_TEXTURE_2D, name);
269 if (!gl_info->gl_ops.gl.p_glGetError())
271 tex_target = GL_TEXTURE_2D;
272 tex_type_str = "2d";
274 else
276 glBindTexture(GL_TEXTURE_2D, old_texture);
277 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_texture);
279 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, name);
280 if (gl_info->gl_ops.gl.p_glGetError())
282 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, old_texture);
283 FIXME("Cannot find type of texture %d.\n", name);
284 return;
286 tex_target = GL_TEXTURE_RECTANGLE_ARB;
287 tex_type_str = "rectangle";
290 glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
291 glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_WIDTH, &width);
292 glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_HEIGHT, &height);
295 FIXME(" %s: %s texture %d, %dx%d, format %#x.\n", debug_fboattachment(attachment),
296 tex_type_str, name, width, height, fmt);
298 glBindTexture(tex_target, old_texture);
300 else if (type == GL_NONE)
302 FIXME("\t%s: NONE.\n", debug_fboattachment(attachment));
304 else
305 ERR("\t%s: Unknown attachment %#x.\n", debug_fboattachment(attachment), type);
308 /* Context activation is done by the caller. */
309 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
311 const struct wined3d_gl_info *gl_info = context->gl_info;
312 GLenum status;
314 if (!FIXME_ON(d3d)) return;
316 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
317 if (status == GL_FRAMEBUFFER_COMPLETE)
319 TRACE("FBO complete\n");
321 else
323 unsigned int i;
325 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
327 if (!context->current_fbo)
329 ERR("FBO 0 is incomplete, driver bug?\n");
330 return;
333 context_dump_fbo_attachment(gl_info, target, GL_DEPTH_ATTACHMENT);
334 context_dump_fbo_attachment(gl_info, target, GL_STENCIL_ATTACHMENT);
336 for (i = 0; i < gl_info->limits.buffers; ++i)
337 context_dump_fbo_attachment(gl_info, target, GL_COLOR_ATTACHMENT0 + i);
338 checkGLcall("Dump FBO attachments");
342 static inline DWORD context_generate_rt_mask(GLenum buffer)
344 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
345 return buffer ? (1u << 31) | buffer : 0;
348 static inline DWORD context_generate_rt_mask_from_resource(struct wined3d_resource *resource)
350 if (resource->type != WINED3D_RTYPE_TEXTURE_2D)
352 FIXME("Not implemented for %s resources.\n", debug_d3dresourcetype(resource->type));
353 return 0;
356 return (1u << 31) | wined3d_texture_get_gl_buffer(texture_from_resource(resource));
359 static inline void context_set_fbo_key_for_surface(const struct wined3d_context *context,
360 struct wined3d_fbo_entry_key *key, UINT idx, struct wined3d_surface *surface,
361 DWORD location)
363 if (!surface)
365 key->objects[idx].object = 0;
366 key->objects[idx].target = 0;
367 key->objects[idx].level = key->objects[idx].layer = 0;
369 else if (surface->current_renderbuffer)
371 key->objects[idx].object = surface->current_renderbuffer->id;
372 key->objects[idx].target = 0;
373 key->objects[idx].level = key->objects[idx].layer = 0;
374 key->rb_namespace |= 1 << idx;
376 else
378 switch (location)
380 case WINED3D_LOCATION_TEXTURE_RGB:
381 key->objects[idx].object = surface_get_texture_name(surface, context, FALSE);
382 key->objects[idx].target = surface->texture_target;
383 key->objects[idx].level = surface->texture_level;
384 key->objects[idx].layer = surface->texture_layer;
385 break;
387 case WINED3D_LOCATION_TEXTURE_SRGB:
388 key->objects[idx].object = surface_get_texture_name(surface, context, TRUE);
389 key->objects[idx].target = surface->texture_target;
390 key->objects[idx].level = surface->texture_level;
391 key->objects[idx].layer = surface->texture_layer;
392 break;
394 case WINED3D_LOCATION_RB_MULTISAMPLE:
395 key->objects[idx].object = surface->container->rb_multisample;
396 key->objects[idx].target = 0;
397 key->objects[idx].level = key->objects[idx].layer = 0;
398 key->rb_namespace |= 1 << idx;
399 break;
401 case WINED3D_LOCATION_RB_RESOLVED:
402 key->objects[idx].object = surface->container->rb_resolved;
403 key->objects[idx].target = 0;
404 key->objects[idx].level = key->objects[idx].layer = 0;
405 key->rb_namespace |= 1 << idx;
406 break;
411 static void context_generate_fbo_key(const struct wined3d_context *context,
412 struct wined3d_fbo_entry_key *key, struct wined3d_surface **render_targets,
413 struct wined3d_surface *depth_stencil, DWORD color_location,
414 DWORD ds_location)
416 UINT i;
418 key->rb_namespace = 0;
419 context_set_fbo_key_for_surface(context, key, 0, depth_stencil, ds_location);
421 for (i = 0; i < context->gl_info->limits.buffers; ++i)
422 context_set_fbo_key_for_surface(context, key, i + 1, render_targets[i], color_location);
425 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
426 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
427 DWORD color_location, DWORD ds_location)
429 const struct wined3d_gl_info *gl_info = context->gl_info;
430 struct fbo_entry *entry;
431 UINT object_count = gl_info->limits.buffers + 1;
433 entry = HeapAlloc(GetProcessHeap(), 0,
434 FIELD_OFFSET(struct fbo_entry, key.objects[object_count]));
435 memset(&entry->key, 0, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count]));
436 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
437 entry->flags = 0;
438 if (depth_stencil)
440 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
441 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
442 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
443 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
445 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
446 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
447 checkGLcall("glGenFramebuffers()");
448 TRACE("Created FBO %u.\n", entry->id);
450 return entry;
453 /* Context activation is done by the caller. */
454 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
455 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
456 DWORD color_location, DWORD ds_location, struct fbo_entry *entry)
458 const struct wined3d_gl_info *gl_info = context->gl_info;
460 context_bind_fbo(context, target, entry->id);
461 context_clean_fbo_attachments(gl_info, target);
463 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
464 entry->flags = 0;
465 if (depth_stencil)
467 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
468 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
469 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
470 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
474 /* Context activation is done by the caller. */
475 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
477 if (entry->id)
479 TRACE("Destroy FBO %u.\n", entry->id);
480 context_destroy_fbo(context, entry->id);
482 --context->fbo_entry_count;
483 list_remove(&entry->entry);
484 HeapFree(GetProcessHeap(), 0, entry);
487 /* Context activation is done by the caller. */
488 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
489 struct wined3d_surface **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 wined3d_texture *rt_texture, *ds_texture;
495 struct fbo_entry *entry;
496 unsigned int i;
498 if (depth_stencil && render_targets[0])
500 rt_texture = render_targets[0]->container;
501 ds_texture = depth_stencil->container;
503 if (wined3d_texture_get_level_width(ds_texture, depth_stencil->texture_level)
504 < wined3d_texture_get_level_width(rt_texture, render_targets[0]->texture_level)
505 || wined3d_texture_get_level_height(ds_texture, depth_stencil->texture_level)
506 < wined3d_texture_get_level_height(rt_texture, render_targets[0]->texture_level))
508 WARN("Depth stencil is smaller than the primary color buffer, disabling.\n");
509 depth_stencil = NULL;
511 else if (ds_texture->resource.multisample_type != rt_texture->resource.multisample_type
512 || ds_texture->resource.multisample_quality != rt_texture->resource.multisample_quality)
514 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
515 rt_texture->resource.multisample_type, rt_texture->resource.multisample_quality,
516 ds_texture->resource.multisample_type, ds_texture->resource.multisample_quality);
517 depth_stencil = NULL;
519 else
520 surface_set_compatible_renderbuffer(depth_stencil, render_targets[0]);
523 context_generate_fbo_key(context, context->fbo_key, render_targets, depth_stencil, color_location,
524 ds_location);
526 if (TRACE_ON(d3d))
528 TRACE("Dumping FBO attachments:\n");
529 for (i = 0; i < gl_info->limits.buffers; ++i)
531 if (render_targets[i])
533 rt_texture = render_targets[i]->container;
534 TRACE(" Color attachment %u: %p format %s, %s %u, %ux%u, %u samples.\n",
535 i, render_targets[i], debug_d3dformat(rt_texture->resource.format->id),
536 context->fbo_key->rb_namespace & (1 << (i + 1)) ? "renderbuffer" : "texure",
537 context->fbo_key->objects[i + 1].object,
538 wined3d_texture_get_level_pow2_width(rt_texture, render_targets[i]->texture_level),
539 wined3d_texture_get_level_pow2_height(rt_texture, render_targets[i]->texture_level),
540 rt_texture->resource.multisample_type);
543 if (depth_stencil)
545 ds_texture = depth_stencil->container;
546 TRACE(" Depth attachment: %p format %s, %s %u, %ux%u, %u samples.\n",
547 depth_stencil, debug_d3dformat(ds_texture->resource.format->id),
548 context->fbo_key->rb_namespace & (1 << 0) ? "renderbuffer" : "texure",
549 context->fbo_key->objects[0].object,
550 wined3d_texture_get_level_pow2_width(ds_texture, depth_stencil->texture_level),
551 wined3d_texture_get_level_pow2_height(ds_texture, depth_stencil->texture_level),
552 ds_texture->resource.multisample_type);
556 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
558 if (memcmp(context->fbo_key, &entry->key, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count])))
559 continue;
561 list_remove(&entry->entry);
562 list_add_head(&context->fbo_list, &entry->entry);
563 return entry;
566 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
568 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
569 list_add_head(&context->fbo_list, &entry->entry);
570 ++context->fbo_entry_count;
572 else
574 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
575 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
576 list_remove(&entry->entry);
577 list_add_head(&context->fbo_list, &entry->entry);
580 return entry;
583 /* Context activation is done by the caller. */
584 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
586 const struct wined3d_gl_info *gl_info = context->gl_info;
587 unsigned int i;
588 GLuint read_binding, draw_binding;
590 if (entry->flags & WINED3D_FBO_ENTRY_FLAG_ATTACHED)
592 context_bind_fbo(context, target, entry->id);
593 return;
596 read_binding = context->fbo_read_binding;
597 draw_binding = context->fbo_draw_binding;
598 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
600 /* Apply render targets */
601 for (i = 0; i < gl_info->limits.buffers; ++i)
603 context_attach_surface_fbo(context, target, i, &entry->key.objects[i + 1],
604 entry->key.rb_namespace & (1 << (i + 1)));
607 context_attach_depth_stencil_fbo(context, target, &entry->key.objects[0],
608 entry->key.rb_namespace & 0x1, entry->flags);
610 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
611 * GL contexts requirements. */
612 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
613 context_set_draw_buffer(context, GL_NONE);
614 if (target != GL_FRAMEBUFFER)
616 if (target == GL_READ_FRAMEBUFFER)
617 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
618 else
619 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
622 entry->flags |= WINED3D_FBO_ENTRY_FLAG_ATTACHED;
625 /* Context activation is done by the caller. */
626 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
627 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
628 DWORD color_location, DWORD ds_location)
630 struct fbo_entry *entry, *entry2;
632 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
634 context_destroy_fbo_entry(context, entry);
637 if (context->rebind_fbo)
639 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
640 context->rebind_fbo = FALSE;
643 if (color_location == WINED3D_LOCATION_DRAWABLE)
645 context->current_fbo = NULL;
646 context_bind_fbo(context, target, 0);
648 else
650 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
651 color_location, ds_location);
652 context_apply_fbo_entry(context, target, context->current_fbo);
656 /* Context activation is done by the caller. */
657 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
658 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
660 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
662 context->blit_targets[0] = render_target;
663 if (clear_size)
664 memset(&context->blit_targets[1], 0, clear_size);
665 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
668 /* Context activation is done by the caller. */
669 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
671 const struct wined3d_gl_info *gl_info = context->gl_info;
673 if (context->free_occlusion_query_count)
675 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
677 else
679 if (gl_info->supported[ARB_OCCLUSION_QUERY])
681 GL_EXTCALL(glGenQueries(1, &query->id));
682 checkGLcall("glGenQueries");
684 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
686 else
688 WARN("Occlusion queries not supported, not allocating query id.\n");
689 query->id = 0;
693 query->context = context;
694 list_add_head(&context->occlusion_queries, &query->entry);
697 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
699 struct wined3d_context *context = query->context;
701 list_remove(&query->entry);
702 query->context = NULL;
704 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
706 UINT new_size = context->free_occlusion_query_size << 1;
707 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
708 new_size * sizeof(*context->free_occlusion_queries));
710 if (!new_data)
712 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
713 return;
716 context->free_occlusion_query_size = new_size;
717 context->free_occlusion_queries = new_data;
720 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
723 /* Context activation is done by the caller. */
724 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
726 const struct wined3d_gl_info *gl_info = context->gl_info;
728 if (context->free_event_query_count)
730 query->object = context->free_event_queries[--context->free_event_query_count];
732 else
734 if (gl_info->supported[ARB_SYNC])
736 /* Using ARB_sync, not much to do here. */
737 query->object.sync = NULL;
738 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
740 else if (gl_info->supported[APPLE_FENCE])
742 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
743 checkGLcall("glGenFencesAPPLE");
745 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
747 else if(gl_info->supported[NV_FENCE])
749 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
750 checkGLcall("glGenFencesNV");
752 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
754 else
756 WARN("Event queries not supported, not allocating query id.\n");
757 query->object.id = 0;
761 query->context = context;
762 list_add_head(&context->event_queries, &query->entry);
765 void context_free_event_query(struct wined3d_event_query *query)
767 struct wined3d_context *context = query->context;
769 list_remove(&query->entry);
770 query->context = NULL;
772 if (context->free_event_query_count >= context->free_event_query_size - 1)
774 UINT new_size = context->free_event_query_size << 1;
775 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
776 new_size * sizeof(*context->free_event_queries));
778 if (!new_data)
780 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
781 return;
784 context->free_event_query_size = new_size;
785 context->free_event_queries = new_data;
788 context->free_event_queries[context->free_event_query_count++] = query->object;
791 /* Context activation is done by the caller. */
792 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
794 const struct wined3d_gl_info *gl_info = context->gl_info;
796 if (context->free_timestamp_query_count)
798 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
800 else
802 GL_EXTCALL(glGenQueries(1, &query->id));
803 checkGLcall("glGenQueries");
805 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
808 query->context = context;
809 list_add_head(&context->timestamp_queries, &query->entry);
812 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
814 struct wined3d_context *context = query->context;
816 list_remove(&query->entry);
817 query->context = NULL;
819 if (context->free_timestamp_query_count >= context->free_timestamp_query_size - 1)
821 UINT new_size = context->free_timestamp_query_size << 1;
822 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_timestamp_queries,
823 new_size * sizeof(*context->free_timestamp_queries));
825 if (!new_data)
827 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
828 return;
831 context->free_timestamp_query_size = new_size;
832 context->free_timestamp_queries = new_data;
835 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
838 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
840 static void context_enum_fbo_entries(const struct wined3d_device *device,
841 GLuint name, BOOL rb_namespace, context_fbo_entry_func_t *callback)
843 UINT i;
845 for (i = 0; i < device->context_count; ++i)
847 struct wined3d_context *context = device->contexts[i];
848 const struct wined3d_gl_info *gl_info = context->gl_info;
849 struct fbo_entry *entry, *entry2;
851 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
853 UINT j;
855 for (j = 0; j < gl_info->limits.buffers + 1; ++j)
857 if (entry->key.objects[j].object == name
858 && !(entry->key.rb_namespace & (1 << j)) == !rb_namespace)
860 callback(context, entry);
861 break;
868 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
870 list_remove(&entry->entry);
871 list_add_head(&context->fbo_destroy_list, &entry->entry);
874 void context_resource_released(const struct wined3d_device *device,
875 struct wined3d_resource *resource, enum wined3d_resource_type type)
877 struct wined3d_texture *texture;
878 UINT i;
880 if (!device->d3d_initialized)
881 return;
883 switch (type)
885 case WINED3D_RTYPE_TEXTURE_2D:
886 case WINED3D_RTYPE_TEXTURE_3D:
887 texture = texture_from_resource(resource);
889 for (i = 0; i < device->context_count; ++i)
891 struct wined3d_context *context = device->contexts[i];
892 if (context->current_rt.texture == texture)
894 context->current_rt.texture = NULL;
895 context->current_rt.sub_resource_idx = 0;
898 break;
900 default:
901 break;
905 void context_gl_resource_released(struct wined3d_device *device,
906 GLuint name, BOOL rb_namespace)
908 context_enum_fbo_entries(device, name, rb_namespace, context_queue_fbo_entry_destruction);
911 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
913 const struct wined3d_gl_info *gl_info = context->gl_info;
914 struct fbo_entry *entry = context->current_fbo;
915 unsigned int i;
917 if (!entry || context->rebind_fbo) return;
919 for (i = 0; i < gl_info->limits.buffers + 1; ++i)
921 if (surface->container->texture_rgb.name == entry->key.objects[i].object
922 || surface->container->texture_srgb.name == entry->key.objects[i].object)
924 TRACE("Updated surface %p is bound as attachment %u to the current FBO.\n", surface, i);
925 context->rebind_fbo = TRUE;
926 return;
931 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
933 const struct wined3d_gl_info *gl_info = ctx->gl_info;
934 BOOL ret = FALSE;
936 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
938 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
940 HDC dc = GetDCEx(ctx->restore_pf_win, 0, DCX_USESTYLE | DCX_CACHE);
941 if (dc)
943 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
945 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
946 ctx->restore_pf, ctx->restore_pf_win);
948 ReleaseDC(ctx->restore_pf_win, dc);
951 else
953 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
957 ctx->restore_pf = 0;
958 ctx->restore_pf_win = NULL;
959 return ret;
962 static BOOL context_set_pixel_format(struct wined3d_context *context, HDC dc, BOOL private, int format)
964 const struct wined3d_gl_info *gl_info = context->gl_info;
965 int current;
967 if (dc == context->hdc && context->hdc_is_private && context->hdc_has_format)
968 return TRUE;
970 current = gl_info->gl_ops.wgl.p_wglGetPixelFormat(dc);
971 if (current == format) goto success;
973 if (!current)
975 if (!SetPixelFormat(dc, format, NULL))
977 /* This may also happen if the dc belongs to a destroyed window. */
978 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
979 format, dc, GetLastError());
980 return FALSE;
983 context->restore_pf = 0;
984 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
985 goto success;
988 /* By default WGL doesn't allow pixel format adjustments but we need it
989 * here. For this reason there's a Wine specific wglSetPixelFormat()
990 * which allows us to set the pixel format multiple times. Only use it
991 * when really needed. */
992 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
994 HWND win;
996 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
998 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
999 format, dc);
1000 return FALSE;
1003 win = private ? NULL : WindowFromDC(dc);
1004 if (win != context->restore_pf_win)
1006 context_restore_pixel_format(context);
1008 context->restore_pf = private ? 0 : current;
1009 context->restore_pf_win = win;
1012 goto success;
1015 /* OpenGL doesn't allow pixel format adjustments. Print an error and
1016 * continue using the old format. There's a big chance that the old
1017 * format works although with a performance hit and perhaps rendering
1018 * errors. */
1019 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
1020 format, dc, current);
1021 return TRUE;
1023 success:
1024 if (dc == context->hdc && context->hdc_is_private)
1025 context->hdc_has_format = TRUE;
1026 return TRUE;
1029 static BOOL context_set_gl_context(struct wined3d_context *ctx)
1031 struct wined3d_swapchain *swapchain = ctx->swapchain;
1032 BOOL backup = FALSE;
1034 if (!context_set_pixel_format(ctx, ctx->hdc, ctx->hdc_is_private, ctx->pixel_format))
1036 WARN("Failed to set pixel format %d on device context %p.\n",
1037 ctx->pixel_format, ctx->hdc);
1038 backup = TRUE;
1041 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
1043 HDC dc;
1045 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
1046 ctx->glCtx, ctx->hdc, GetLastError());
1047 ctx->valid = 0;
1048 WARN("Trying fallback to the backup window.\n");
1050 /* FIXME: If the context is destroyed it's no longer associated with
1051 * a swapchain, so we can't use the swapchain to get a backup dc. To
1052 * make this work windowless contexts would need to be handled by the
1053 * device. */
1054 if (ctx->destroyed)
1056 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
1057 context_set_current(NULL);
1058 return FALSE;
1061 if (!(dc = swapchain_get_backup_dc(swapchain)))
1063 context_set_current(NULL);
1064 return FALSE;
1067 if (!context_set_pixel_format(ctx, dc, TRUE, ctx->pixel_format))
1069 ERR("Failed to set pixel format %d on device context %p.\n",
1070 ctx->pixel_format, dc);
1071 context_set_current(NULL);
1072 return FALSE;
1075 if (!wglMakeCurrent(dc, ctx->glCtx))
1077 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
1078 dc, GetLastError());
1079 context_set_current(NULL);
1080 return FALSE;
1083 ctx->valid = 1;
1085 ctx->needs_set = 0;
1086 return TRUE;
1089 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
1091 if (!wglMakeCurrent(dc, gl_ctx))
1093 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1094 gl_ctx, dc, GetLastError());
1095 context_set_current(NULL);
1099 static void context_update_window(struct wined3d_context *context)
1101 if (context->win_handle == context->swapchain->win_handle)
1102 return;
1104 TRACE("Updating context %p window from %p to %p.\n",
1105 context, context->win_handle, context->swapchain->win_handle);
1107 if (context->hdc)
1108 wined3d_release_dc(context->win_handle, context->hdc);
1110 context->win_handle = context->swapchain->win_handle;
1111 context->hdc_is_private = FALSE;
1112 context->hdc_has_format = FALSE;
1113 context->needs_set = 1;
1114 context->valid = 1;
1116 if (!(context->hdc = GetDCEx(context->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1118 ERR("Failed to get a device context for window %p.\n", context->win_handle);
1119 context->valid = 0;
1123 static void context_destroy_gl_resources(struct wined3d_context *context)
1125 const struct wined3d_gl_info *gl_info = context->gl_info;
1126 struct wined3d_timestamp_query *timestamp_query;
1127 struct wined3d_occlusion_query *occlusion_query;
1128 struct wined3d_event_query *event_query;
1129 struct fbo_entry *entry, *entry2;
1130 HGLRC restore_ctx;
1131 HDC restore_dc;
1132 unsigned int i;
1134 restore_ctx = wglGetCurrentContext();
1135 restore_dc = wglGetCurrentDC();
1137 if (restore_ctx == context->glCtx)
1138 restore_ctx = NULL;
1139 else if (context->valid)
1140 context_set_gl_context(context);
1142 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
1144 if (context->valid)
1145 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
1146 timestamp_query->context = NULL;
1149 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1151 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1152 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1153 occlusion_query->context = NULL;
1156 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
1158 if (context->valid)
1160 if (gl_info->supported[ARB_SYNC])
1162 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
1164 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
1165 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
1167 event_query->context = NULL;
1170 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1172 if (!context->valid) entry->id = 0;
1173 context_destroy_fbo_entry(context, entry);
1176 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1178 if (!context->valid) entry->id = 0;
1179 context_destroy_fbo_entry(context, entry);
1182 if (context->valid)
1184 if (context->dummy_arbfp_prog)
1186 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1189 if (gl_info->supported[ARB_TIMER_QUERY])
1190 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1192 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1193 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1195 if (gl_info->supported[ARB_SYNC])
1197 for (i = 0; i < context->free_event_query_count; ++i)
1199 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
1202 else if (gl_info->supported[APPLE_FENCE])
1204 for (i = 0; i < context->free_event_query_count; ++i)
1206 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1209 else if (gl_info->supported[NV_FENCE])
1211 for (i = 0; i < context->free_event_query_count; ++i)
1213 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1217 checkGLcall("context cleanup");
1220 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1221 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1222 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1224 context_restore_pixel_format(context);
1225 if (restore_ctx)
1227 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1229 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1231 ERR("Failed to disable GL context.\n");
1234 wined3d_release_dc(context->win_handle, context->hdc);
1236 if (!wglDeleteContext(context->glCtx))
1238 DWORD err = GetLastError();
1239 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1243 DWORD context_get_tls_idx(void)
1245 return wined3d_context_tls_idx;
1248 void context_set_tls_idx(DWORD idx)
1250 wined3d_context_tls_idx = idx;
1253 struct wined3d_context *context_get_current(void)
1255 return TlsGetValue(wined3d_context_tls_idx);
1258 BOOL context_set_current(struct wined3d_context *ctx)
1260 struct wined3d_context *old = context_get_current();
1262 if (old == ctx)
1264 TRACE("Already using D3D context %p.\n", ctx);
1265 return TRUE;
1268 if (old)
1270 if (old->destroyed)
1272 TRACE("Switching away from destroyed context %p.\n", old);
1273 context_destroy_gl_resources(old);
1274 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1275 HeapFree(GetProcessHeap(), 0, old);
1277 else
1279 if (wglGetCurrentContext())
1281 TRACE("Flushing context %p before switching to %p.\n", old, ctx);
1282 glFlush();
1284 old->current = 0;
1288 if (ctx)
1290 if (!ctx->valid)
1292 ERR("Trying to make invalid context %p current\n", ctx);
1293 return FALSE;
1296 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1297 if (!context_set_gl_context(ctx))
1298 return FALSE;
1299 ctx->current = 1;
1301 else if(wglGetCurrentContext())
1303 TRACE("Clearing current D3D context.\n");
1304 if (!wglMakeCurrent(NULL, NULL))
1306 DWORD err = GetLastError();
1307 ERR("Failed to clear current GL context, last error %#x.\n", err);
1308 TlsSetValue(wined3d_context_tls_idx, NULL);
1309 return FALSE;
1313 return TlsSetValue(wined3d_context_tls_idx, ctx);
1316 void context_release(struct wined3d_context *context)
1318 TRACE("Releasing context %p, level %u.\n", context, context->level);
1320 if (WARN_ON(d3d))
1322 if (!context->level)
1323 WARN("Context %p is not active.\n", context);
1324 else if (context != context_get_current())
1325 WARN("Context %p is not the current context.\n", context);
1328 if (!--context->level)
1330 if (context_restore_pixel_format(context))
1331 context->needs_set = 1;
1332 if (context->restore_ctx)
1334 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1335 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1336 context->restore_ctx = NULL;
1337 context->restore_dc = NULL;
1342 /* This is used when a context for render target A is active, but a separate context is
1343 * needed to access the WGL framebuffer for render target B. Re-acquire a context for rt
1344 * A to avoid breaking caller code. */
1345 void context_restore(struct wined3d_context *context, struct wined3d_surface *restore)
1347 if (context->current_rt.texture != restore->container
1348 || context->current_rt.sub_resource_idx != surface_get_sub_resource_idx(restore))
1350 context_release(context);
1351 context = context_acquire(restore->container->resource.device, restore);
1354 context_release(context);
1357 static void context_enter(struct wined3d_context *context)
1359 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1361 if (!context->level++)
1363 const struct wined3d_context *current_context = context_get_current();
1364 HGLRC current_gl = wglGetCurrentContext();
1366 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1368 TRACE("Another GL context (%p on device context %p) is already current.\n",
1369 current_gl, wglGetCurrentDC());
1370 context->restore_ctx = current_gl;
1371 context->restore_dc = wglGetCurrentDC();
1372 context->needs_set = 1;
1374 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1375 && context->pixel_format != context->gl_info->gl_ops.wgl.p_wglGetPixelFormat(context->hdc))
1376 context->needs_set = 1;
1380 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1382 DWORD rep = context->state_table[state].representative;
1383 DWORD idx;
1384 BYTE shift;
1386 if (isStateDirty(context, rep)) return;
1388 context->dirtyArray[context->numDirtyEntries++] = rep;
1389 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1390 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1391 context->isStateDirty[idx] |= (1u << shift);
1394 /* This function takes care of wined3d pixel format selection. */
1395 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1396 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1397 BOOL auxBuffers, BOOL findCompatible)
1399 int iPixelFormat=0;
1400 unsigned int current_value;
1401 unsigned int cfg_count = device->adapter->cfg_count;
1402 unsigned int i;
1404 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1405 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1406 auxBuffers, findCompatible);
1408 current_value = 0;
1409 for (i = 0; i < cfg_count; ++i)
1411 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1412 unsigned int value;
1414 /* For now only accept RGBA formats. Perhaps some day we will
1415 * allow floating point formats for pbuffers. */
1416 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1417 continue;
1418 /* In window mode we need a window drawable format and double buffering. */
1419 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1420 continue;
1421 if (cfg->redSize < color_format->red_size)
1422 continue;
1423 if (cfg->greenSize < color_format->green_size)
1424 continue;
1425 if (cfg->blueSize < color_format->blue_size)
1426 continue;
1427 if (cfg->alphaSize < color_format->alpha_size)
1428 continue;
1429 if (cfg->depthSize < ds_format->depth_size)
1430 continue;
1431 if (ds_format->stencil_size && cfg->stencilSize != ds_format->stencil_size)
1432 continue;
1433 /* Check multisampling support. */
1434 if (cfg->numSamples)
1435 continue;
1437 value = 1;
1438 /* We try to locate a format which matches our requirements exactly. In case of
1439 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1440 if (cfg->depthSize == ds_format->depth_size)
1441 value += 1;
1442 if (cfg->stencilSize == ds_format->stencil_size)
1443 value += 2;
1444 if (cfg->alphaSize == color_format->alpha_size)
1445 value += 4;
1446 /* We like to have aux buffers in backbuffer mode */
1447 if (auxBuffers && cfg->auxBuffers)
1448 value += 8;
1449 if (cfg->redSize == color_format->red_size
1450 && cfg->greenSize == color_format->green_size
1451 && cfg->blueSize == color_format->blue_size)
1452 value += 16;
1454 if (value > current_value)
1456 iPixelFormat = cfg->iPixelFormat;
1457 current_value = value;
1461 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1462 if(!iPixelFormat && !findCompatible) {
1463 ERR("Can't find a suitable iPixelFormat\n");
1464 return FALSE;
1465 } else if(!iPixelFormat) {
1466 PIXELFORMATDESCRIPTOR pfd;
1468 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1469 /* PixelFormat selection */
1470 ZeroMemory(&pfd, sizeof(pfd));
1471 pfd.nSize = sizeof(pfd);
1472 pfd.nVersion = 1;
1473 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1474 pfd.iPixelType = PFD_TYPE_RGBA;
1475 pfd.cAlphaBits = color_format->alpha_size;
1476 pfd.cColorBits = color_format->red_size + color_format->green_size
1477 + color_format->blue_size + color_format->alpha_size;
1478 pfd.cDepthBits = ds_format->depth_size;
1479 pfd.cStencilBits = ds_format->stencil_size;
1480 pfd.iLayerType = PFD_MAIN_PLANE;
1482 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1483 if(!iPixelFormat) {
1484 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1485 ERR("Can't find a suitable iPixelFormat\n");
1486 return FALSE;
1490 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1491 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1492 return iPixelFormat;
1495 /* Context activation is done by the caller. */
1496 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1498 const struct wined3d_gl_info *gl_info = context->gl_info;
1499 unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1501 for (i = 0; i < count; ++i)
1503 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1504 checkGLcall("glActiveTexture");
1506 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1507 checkGLcall("glBindTexture");
1509 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1511 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1512 checkGLcall("glBindTexture");
1515 if (gl_info->supported[EXT_TEXTURE3D])
1517 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1518 checkGLcall("glBindTexture");
1521 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1523 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1524 checkGLcall("glBindTexture");
1527 if (gl_info->supported[EXT_TEXTURE_ARRAY])
1529 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, device->dummy_texture_2d_array[i]);
1530 checkGLcall("glBindTexture");
1535 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1537 return gl_info->supported[ARB_DEBUG_OUTPUT]
1538 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1541 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1542 GLenum severity, GLsizei length, const char *message, void *ctx)
1544 switch (type)
1546 case GL_DEBUG_TYPE_ERROR_ARB:
1547 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1548 break;
1550 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1551 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1552 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1553 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1554 break;
1556 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1557 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1558 break;
1560 default:
1561 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1562 break;
1566 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1568 HGLRC ctx;
1569 unsigned int ctx_attrib_idx = 0;
1570 GLint ctx_attribs[7], ctx_flags = 0;
1572 if (context_debug_output_enabled(gl_info))
1573 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1574 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1575 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1576 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1577 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1578 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1579 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1580 if (ctx_flags)
1582 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1583 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1585 ctx_attribs[ctx_attrib_idx] = 0;
1587 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1589 if (ctx_flags & WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
1591 ctx_attribs[ctx_attrib_idx - 1] &= ~WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1592 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1593 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1594 GetLastError());
1597 return ctx;
1600 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1601 struct wined3d_texture *target, const struct wined3d_format *ds_format)
1603 struct wined3d_device *device = swapchain->device;
1604 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1605 const struct wined3d_format *color_format;
1606 struct wined3d_context *ret;
1607 BOOL auxBuffers = FALSE;
1608 HGLRC ctx, share_ctx;
1609 int pixel_format;
1610 unsigned int s;
1611 DWORD state;
1612 HDC hdc = 0;
1613 BOOL hdc_is_private = FALSE;
1615 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1617 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1618 if (!ret)
1619 return NULL;
1621 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1622 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1623 if (!ret->blit_targets)
1624 goto out;
1626 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1627 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1628 if (!ret->draw_buffers)
1629 goto out;
1631 ret->fbo_key = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1632 FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[gl_info->limits.buffers + 1]));
1633 if (!ret->fbo_key)
1634 goto out;
1636 ret->free_timestamp_query_size = 4;
1637 ret->free_timestamp_queries = HeapAlloc(GetProcessHeap(), 0,
1638 ret->free_timestamp_query_size * sizeof(*ret->free_timestamp_queries));
1639 if (!ret->free_timestamp_queries)
1640 goto out;
1641 list_init(&ret->timestamp_queries);
1643 ret->free_occlusion_query_size = 4;
1644 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1645 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1646 if (!ret->free_occlusion_queries)
1647 goto out;
1649 list_init(&ret->occlusion_queries);
1651 ret->free_event_query_size = 4;
1652 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1653 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1654 if (!ret->free_event_queries)
1655 goto out;
1657 list_init(&ret->event_queries);
1658 list_init(&ret->fbo_list);
1659 list_init(&ret->fbo_destroy_list);
1661 if (!device->shader_backend->shader_allocate_context_data(ret))
1663 ERR("Failed to allocate shader backend context data.\n");
1664 goto out;
1666 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1668 ERR("Failed to allocate fragment pipeline context data.\n");
1669 goto out;
1672 /* Initialize the texture unit mapping to a 1:1 mapping */
1673 for (s = 0; s < MAX_COMBINED_SAMPLERS; ++s)
1675 if (s < gl_info->limits.combined_samplers)
1677 ret->tex_unit_map[s] = s;
1678 ret->rev_tex_unit_map[s] = s;
1680 else
1682 ret->tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1683 ret->rev_tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1687 if (!(hdc = GetDCEx(swapchain->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1689 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1691 if ((hdc = swapchain_get_backup_dc(swapchain)))
1692 hdc_is_private = TRUE;
1693 else
1695 ERR("Failed to retrieve a device context.\n");
1696 goto out;
1700 color_format = target->resource.format;
1702 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1703 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1704 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1706 auxBuffers = TRUE;
1708 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1709 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1710 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1711 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1714 /* DirectDraw supports 8bit paletted render targets and these are used by
1715 * old games like StarCraft and C&C. Most modern hardware doesn't support
1716 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1717 * conversion (ab)uses the alpha component for storing the palette index.
1718 * For this reason we require a format with 8bit alpha, so request
1719 * A8R8G8B8. */
1720 if (color_format->id == WINED3DFMT_P8_UINT)
1721 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1723 /* When "always_offscreen" is enabled, we only use the drawable for
1724 * presentation blits, and don't do any rendering to it. That means we
1725 * don't need depth or stencil buffers, and can mostly ignore the render
1726 * target format. This wouldn't necessarily be quite correct for 10bpc
1727 * display modes, but we don't currently support those.
1728 * Using the same format regardless of the color/depth/stencil targets
1729 * makes it much less likely that different wined3d instances will set
1730 * conflicting pixel formats. */
1731 if (wined3d_settings.offscreen_rendering_mode != ORM_BACKBUFFER
1732 && wined3d_settings.always_offscreen)
1734 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1735 ds_format = wined3d_get_format(gl_info, WINED3DFMT_UNKNOWN);
1738 /* Try to find a pixel format which matches our requirements. */
1739 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1741 /* Try to locate a compatible format if we weren't able to find anything. */
1742 if (!pixel_format)
1744 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1745 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1748 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1749 if (!pixel_format)
1751 ERR("Can't find a suitable pixel format.\n");
1752 goto out;
1755 ret->gl_info = gl_info;
1757 context_enter(ret);
1759 if (!context_set_pixel_format(ret, hdc, hdc_is_private, pixel_format))
1761 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1762 context_release(ret);
1763 goto out;
1766 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1767 if (gl_info->p_wglCreateContextAttribsARB)
1769 if (!(ctx = context_create_wgl_attribs(gl_info, hdc, share_ctx)))
1770 goto out;
1772 else
1774 if (!(ctx = wglCreateContext(hdc)))
1776 ERR("Failed to create a WGL context.\n");
1777 context_release(ret);
1778 goto out;
1781 if (share_ctx && !wglShareLists(share_ctx, ctx))
1783 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1784 context_release(ret);
1785 if (!wglDeleteContext(ctx))
1786 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1787 goto out;
1791 if (!device_context_add(device, ret))
1793 ERR("Failed to add the newly created context to the context list\n");
1794 context_release(ret);
1795 if (!wglDeleteContext(ctx))
1796 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1797 goto out;
1800 ret->d3d_info = &device->adapter->d3d_info;
1801 ret->state_table = device->StateTable;
1803 /* Mark all states dirty to force a proper initialization of the states
1804 * on the first use of the context. */
1805 for (state = 0; state <= STATE_HIGHEST; ++state)
1807 if (ret->state_table[state].representative)
1808 context_invalidate_state(ret, state);
1811 ret->swapchain = swapchain;
1812 ret->current_rt.texture = target;
1813 ret->current_rt.sub_resource_idx = 0;
1814 ret->tid = GetCurrentThreadId();
1816 ret->render_offscreen = wined3d_resource_is_offscreen(&target->resource);
1817 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1818 ret->valid = 1;
1820 ret->glCtx = ctx;
1821 ret->win_handle = swapchain->win_handle;
1822 ret->hdc = hdc;
1823 ret->hdc_is_private = hdc_is_private;
1824 ret->hdc_has_format = TRUE;
1825 ret->pixel_format = pixel_format;
1826 ret->needs_set = 1;
1828 /* Set up the context defaults */
1829 if (!context_set_current(ret))
1831 ERR("Cannot activate context to set up defaults.\n");
1832 device_context_remove(device, ret);
1833 context_release(ret);
1834 if (!wglDeleteContext(ctx))
1835 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1836 goto out;
1839 if (context_debug_output_enabled(gl_info))
1841 GL_EXTCALL(glDebugMessageCallback(wined3d_debug_callback, ret));
1842 if (TRACE_ON(d3d_synchronous))
1843 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
1844 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
1845 if (ERR_ON(d3d))
1847 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR,
1848 GL_DONT_CARE, 0, NULL, GL_TRUE));
1850 if (FIXME_ON(d3d))
1852 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
1853 GL_DONT_CARE, 0, NULL, GL_TRUE));
1854 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
1855 GL_DONT_CARE, 0, NULL, GL_TRUE));
1856 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY,
1857 GL_DONT_CARE, 0, NULL, GL_TRUE));
1859 if (WARN_ON(d3d_perf))
1861 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE,
1862 GL_DONT_CARE, 0, NULL, GL_TRUE));
1866 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1868 TRACE("Setting up the screen\n");
1870 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
1872 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1873 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1875 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1876 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1878 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1879 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1881 else
1883 GLuint vao;
1885 GL_EXTCALL(glGenVertexArrays(1, &vao));
1886 GL_EXTCALL(glBindVertexArray(vao));
1887 checkGLcall("creating VAO");
1890 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1891 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1892 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1893 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1895 if (gl_info->supported[ARB_VERTEX_BLEND])
1897 /* Direct3D always uses n-1 weights for n world matrices and uses
1898 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1899 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1900 * enabled as well. */
1901 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1902 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1904 if (gl_info->supported[NV_TEXTURE_SHADER2])
1906 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1907 * the previous texture where to source the offset from is always unit - 1.
1909 for (s = 1; s < gl_info->limits.textures; ++s)
1911 context_active_texture(ret, gl_info, s);
1912 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1913 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1914 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1917 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1919 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1920 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1921 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1922 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1923 * is ever assigned.
1925 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1926 * program and the dummy program is destroyed when the context is destroyed.
1928 static const char dummy_program[] =
1929 "!!ARBfp1.0\n"
1930 "MOV result.color, fragment.color.primary;\n"
1931 "END\n";
1932 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1933 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1934 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1937 if (gl_info->supported[ARB_POINT_SPRITE])
1939 for (s = 0; s < gl_info->limits.textures; ++s)
1941 context_active_texture(ret, gl_info, s);
1942 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1943 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1947 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1949 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1951 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1953 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1955 device->shader_backend->shader_init_context_state(ret);
1956 ret->shader_update_mask = (1u << WINED3D_SHADER_TYPE_PIXEL)
1957 | (1u << WINED3D_SHADER_TYPE_VERTEX)
1958 | (1u << WINED3D_SHADER_TYPE_GEOMETRY)
1959 | (1u << WINED3D_SHADER_TYPE_HULL)
1960 | (1u << WINED3D_SHADER_TYPE_DOMAIN);
1962 /* If this happens to be the first context for the device, dummy textures
1963 * are not created yet. In that case, they will be created (and bound) by
1964 * create_dummy_textures right after this context is initialized. */
1965 if (device->dummy_texture_2d[0])
1966 bind_dummy_textures(device, ret);
1968 TRACE("Created context %p.\n", ret);
1970 return ret;
1972 out:
1973 if (hdc) wined3d_release_dc(swapchain->win_handle, hdc);
1974 device->shader_backend->shader_free_context_data(ret);
1975 device->adapter->fragment_pipe->free_context_data(ret);
1976 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1977 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1978 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
1979 HeapFree(GetProcessHeap(), 0, ret->fbo_key);
1980 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1981 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1982 HeapFree(GetProcessHeap(), 0, ret);
1983 return NULL;
1986 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1988 BOOL destroy;
1990 TRACE("Destroying ctx %p\n", context);
1992 if (context->tid == GetCurrentThreadId() || !context->current)
1994 context_destroy_gl_resources(context);
1995 TlsSetValue(wined3d_context_tls_idx, NULL);
1996 destroy = TRUE;
1998 else
2000 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
2001 in wined3d_adapter may go away in the meantime */
2002 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
2003 *gl_info = *context->gl_info;
2004 context->gl_info = gl_info;
2005 context->destroyed = 1;
2006 destroy = FALSE;
2009 device->shader_backend->shader_free_context_data(context);
2010 device->adapter->fragment_pipe->free_context_data(context);
2011 HeapFree(GetProcessHeap(), 0, context->fbo_key);
2012 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
2013 HeapFree(GetProcessHeap(), 0, context->blit_targets);
2014 device_context_remove(device, context);
2015 if (destroy) HeapFree(GetProcessHeap(), 0, context);
2018 /* Context activation is done by the caller. */
2019 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
2021 const GLdouble projection[] =
2023 2.0 / width, 0.0, 0.0, 0.0,
2024 0.0, 2.0 / height, 0.0, 0.0,
2025 0.0, 0.0, 2.0, 0.0,
2026 -1.0, -1.0, -1.0, 1.0,
2029 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
2030 checkGLcall("glMatrixMode(GL_PROJECTION)");
2031 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
2032 checkGLcall("glLoadMatrixd");
2033 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
2034 checkGLcall("glViewport");
2037 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
2039 const struct wined3d_texture *rt = context->current_rt.texture;
2040 unsigned int level;
2042 if (rt->swapchain && rt->swapchain->front_buffer == rt)
2044 RECT window_size;
2046 GetClientRect(context->win_handle, &window_size);
2047 size->cx = window_size.right - window_size.left;
2048 size->cy = window_size.bottom - window_size.top;
2050 return;
2053 level = context->current_rt.sub_resource_idx % rt->level_count;
2054 size->cx = wined3d_texture_get_level_width(rt, level);
2055 size->cy = wined3d_texture_get_level_height(rt, level);
2058 /*****************************************************************************
2059 * SetupForBlit
2061 * Sets up a context for DirectDraw blitting.
2062 * All texture units are disabled, texture unit 0 is set as current unit
2063 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
2064 * color writing enabled for all channels
2065 * register combiners disabled, shaders disabled
2066 * world matrix is set to identity, texture matrix 0 too
2067 * projection matrix is setup for drawing screen coordinates
2069 * Params:
2070 * This: Device to activate the context for
2071 * context: Context to setup
2073 *****************************************************************************/
2074 /* Context activation is done by the caller. */
2075 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
2077 int i;
2078 const struct wined3d_gl_info *gl_info = context->gl_info;
2079 DWORD sampler;
2080 SIZE rt_size;
2082 TRACE("Setting up context %p for blitting\n", context);
2084 context_get_rt_size(context, &rt_size);
2086 if (context->last_was_blit)
2088 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
2090 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2091 context->blit_w = rt_size.cx;
2092 context->blit_h = rt_size.cy;
2093 /* No need to dirtify here, the states are still dirtified because
2094 * they weren't applied since the last SetupForBlit() call. */
2096 TRACE("Context is already set up for blitting, nothing to do\n");
2097 return;
2099 context->last_was_blit = TRUE;
2101 /* Disable all textures. The caller can then bind a texture it wants to blit
2102 * from
2104 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
2105 * function texture unit. No need to care for higher samplers
2107 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
2109 sampler = context->rev_tex_unit_map[i];
2110 context_active_texture(context, gl_info, i);
2112 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2114 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2115 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2117 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2118 checkGLcall("glDisable GL_TEXTURE_3D");
2119 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2121 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2122 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2124 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2125 checkGLcall("glDisable GL_TEXTURE_2D");
2127 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2128 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
2130 if (sampler != WINED3D_UNMAPPED_STAGE)
2132 if (sampler < MAX_TEXTURES)
2133 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2134 context_invalidate_state(context, STATE_SAMPLER(sampler));
2137 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
2138 GL_EXTCALL(glBindSampler(0, 0));
2139 context_active_texture(context, gl_info, 0);
2141 sampler = context->rev_tex_unit_map[0];
2143 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2145 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2146 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2148 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2149 checkGLcall("glDisable GL_TEXTURE_3D");
2150 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2152 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2153 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2155 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2156 checkGLcall("glDisable GL_TEXTURE_2D");
2158 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2160 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
2161 checkGLcall("glMatrixMode(GL_TEXTURE)");
2162 gl_info->gl_ops.gl.p_glLoadIdentity();
2163 checkGLcall("glLoadIdentity()");
2165 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2167 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
2168 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
2169 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
2172 if (sampler != WINED3D_UNMAPPED_STAGE)
2174 if (sampler < MAX_TEXTURES)
2176 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
2177 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2179 context_invalidate_state(context, STATE_SAMPLER(sampler));
2182 /* Other misc states */
2183 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2184 checkGLcall("glDisable(GL_ALPHA_TEST)");
2185 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2186 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2187 checkGLcall("glDisable GL_LIGHTING");
2188 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2189 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2190 checkGLcall("glDisable GL_DEPTH_TEST");
2191 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2192 glDisableWINE(GL_FOG);
2193 checkGLcall("glDisable GL_FOG");
2194 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
2195 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2196 checkGLcall("glDisable GL_BLEND");
2197 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2198 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2199 checkGLcall("glDisable GL_CULL_FACE");
2200 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2201 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2202 checkGLcall("glDisable GL_STENCIL_TEST");
2203 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2204 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2205 checkGLcall("glDisable GL_SCISSOR_TEST");
2206 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2207 if (gl_info->supported[ARB_POINT_SPRITE])
2209 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2210 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2211 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2213 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2214 checkGLcall("glColorMask");
2215 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2216 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2217 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2218 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2219 if (gl_info->supported[EXT_SECONDARY_COLOR])
2221 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2222 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2223 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2226 /* Setup transforms */
2227 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2228 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2229 gl_info->gl_ops.gl.p_glLoadIdentity();
2230 checkGLcall("glLoadIdentity()");
2231 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2233 context->last_was_rhw = TRUE;
2234 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2236 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2237 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2238 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2239 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2240 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2241 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2242 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2244 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2246 /* Disable shaders */
2247 device->shader_backend->shader_disable(device->shader_priv, context);
2249 context->blit_w = rt_size.cx;
2250 context->blit_h = rt_size.cy;
2251 context_invalidate_state(context, STATE_VIEWPORT);
2252 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2255 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2257 return rt_mask & (1u << 31);
2260 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2262 return rt_mask & ~(1u << 31);
2265 /* Context activation is done by the caller. */
2266 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2268 const struct wined3d_gl_info *gl_info = context->gl_info;
2270 if (!rt_mask)
2272 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2273 checkGLcall("glDrawBuffer()");
2275 else if (is_rt_mask_onscreen(rt_mask))
2277 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2278 checkGLcall("glDrawBuffer()");
2280 else
2282 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2284 unsigned int i = 0;
2286 while (rt_mask)
2288 if (rt_mask & 1)
2289 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2290 else
2291 context->draw_buffers[i] = GL_NONE;
2293 rt_mask >>= 1;
2294 ++i;
2297 if (gl_info->supported[ARB_DRAW_BUFFERS])
2299 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2300 checkGLcall("glDrawBuffers()");
2302 else
2304 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2305 checkGLcall("glDrawBuffer()");
2308 else
2310 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2315 /* Context activation is done by the caller. */
2316 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2318 const struct wined3d_gl_info *gl_info = context->gl_info;
2319 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2320 DWORD new_mask = context_generate_rt_mask(buffer);
2322 if (new_mask == *current_mask)
2323 return;
2325 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2326 checkGLcall("glDrawBuffer()");
2328 *current_mask = new_mask;
2331 /* Context activation is done by the caller. */
2332 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2334 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2335 checkGLcall("glActiveTexture");
2336 context->active_texture = unit;
2339 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2341 const struct wined3d_gl_info *gl_info = context->gl_info;
2342 DWORD unit = context->active_texture;
2343 DWORD old_texture_type = context->texture_type[unit];
2345 if (name)
2347 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2348 checkGLcall("glBindTexture");
2350 else
2352 target = GL_NONE;
2355 if (old_texture_type != target)
2357 const struct wined3d_device *device = context->swapchain->device;
2359 switch (old_texture_type)
2361 case GL_NONE:
2362 /* nothing to do */
2363 break;
2364 case GL_TEXTURE_2D:
2365 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
2366 checkGLcall("glBindTexture");
2367 break;
2368 case GL_TEXTURE_2D_ARRAY:
2369 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, device->dummy_texture_2d_array[unit]);
2370 checkGLcall("glBindTexture");
2371 break;
2372 case GL_TEXTURE_RECTANGLE_ARB:
2373 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
2374 checkGLcall("glBindTexture");
2375 break;
2376 case GL_TEXTURE_CUBE_MAP:
2377 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
2378 checkGLcall("glBindTexture");
2379 break;
2380 case GL_TEXTURE_3D:
2381 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
2382 checkGLcall("glBindTexture");
2383 break;
2384 default:
2385 ERR("Unexpected texture target %#x.\n", old_texture_type);
2388 context->texture_type[unit] = target;
2392 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2394 if (context->render_offscreen == offscreen) return;
2396 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2397 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2398 context_invalidate_state(context, STATE_VIEWPORT);
2399 context_invalidate_state(context, STATE_SCISSORRECT);
2400 context_invalidate_state(context, STATE_FRONTFACE);
2401 context->render_offscreen = offscreen;
2404 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2405 const struct wined3d_format *required)
2407 if (existing == required)
2408 return TRUE;
2409 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2410 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2411 return FALSE;
2412 if (existing->depth_size < required->depth_size)
2413 return FALSE;
2414 /* If stencil bits are used the exact amount is required - otherwise
2415 * wrapping won't work correctly. */
2416 if (required->stencil_size && required->stencil_size != existing->stencil_size)
2417 return FALSE;
2418 return TRUE;
2421 /* Context activation is done by the caller. */
2422 static void context_validate_onscreen_formats(struct wined3d_context *context,
2423 const struct wined3d_rendertarget_view *depth_stencil)
2425 /* Onscreen surfaces are always in a swapchain */
2426 struct wined3d_swapchain *swapchain = context->current_rt.texture->swapchain;
2427 struct wined3d_surface *surface;
2429 if (context->render_offscreen || !depth_stencil) return;
2430 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2432 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2433 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2434 * format. */
2435 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2437 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2438 surface = context->current_rt.texture->sub_resources[context->current_rt.sub_resource_idx].u.surface;
2439 surface_load_location(surface, context, WINED3D_LOCATION_TEXTURE_RGB);
2440 swapchain->render_to_fbo = TRUE;
2441 swapchain_update_draw_bindings(swapchain);
2442 context_set_render_offscreen(context, TRUE);
2445 GLenum context_get_offscreen_gl_buffer(const struct wined3d_context *context)
2447 switch (wined3d_settings.offscreen_rendering_mode)
2449 case ORM_FBO:
2450 return GL_COLOR_ATTACHMENT0;
2452 case ORM_BACKBUFFER:
2453 return context->aux_buffers > 0 ? GL_AUX0 : GL_BACK;
2455 default:
2456 FIXME("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
2457 return GL_BACK;
2461 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_context *context, struct wined3d_texture *rt)
2463 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2464 return 0;
2465 else if (rt->swapchain)
2466 return context_generate_rt_mask_from_resource(&rt->resource);
2467 else
2468 return context_generate_rt_mask(context_get_offscreen_gl_buffer(context));
2471 /* Context activation is done by the caller. */
2472 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2474 struct wined3d_texture *rt = context->current_rt.texture;
2475 struct wined3d_surface *surface;
2476 DWORD rt_mask, *cur_mask;
2478 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2480 context_validate_onscreen_formats(context, NULL);
2482 if (context->render_offscreen)
2484 wined3d_texture_load(rt, context, FALSE);
2486 surface = rt->sub_resources[context->current_rt.sub_resource_idx].u.surface;
2487 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, surface, NULL, rt->resource.draw_binding);
2488 if (rt->resource.format->id != WINED3DFMT_NULL)
2489 rt_mask = 1;
2490 else
2491 rt_mask = 0;
2493 else
2495 context->current_fbo = NULL;
2496 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2497 rt_mask = context_generate_rt_mask_from_resource(&rt->resource);
2500 else
2502 rt_mask = context_generate_rt_mask_no_fbo(context, rt);
2505 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2507 if (rt_mask != *cur_mask)
2509 context_apply_draw_buffers(context, rt_mask);
2510 *cur_mask = rt_mask;
2513 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2515 context_check_fbo_status(context, GL_FRAMEBUFFER);
2518 SetupForBlit(device, context);
2519 context_invalidate_state(context, STATE_FRAMEBUFFER);
2522 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2523 const struct wined3d_rendertarget_view *ds)
2525 unsigned int i;
2527 if (ds) return TRUE;
2529 for (i = 0; i < rt_count; ++i)
2531 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2532 return TRUE;
2535 WARN("Invalid render target config, need at least one attachment.\n");
2536 return FALSE;
2539 /* Context activation is done by the caller. */
2540 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_state *state,
2541 UINT rt_count, const struct wined3d_fb_state *fb)
2543 struct wined3d_rendertarget_view **rts = fb->render_targets;
2544 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2545 const struct wined3d_gl_info *gl_info = context->gl_info;
2546 DWORD rt_mask = 0, *cur_mask;
2547 UINT i;
2549 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != state->fb
2550 || rt_count != gl_info->limits.buffers)
2552 if (!context_validate_rt_config(rt_count, rts, dsv))
2553 return FALSE;
2555 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2557 context_validate_onscreen_formats(context, dsv);
2559 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2561 for (i = 0; i < rt_count; ++i)
2563 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(rts[i]);
2564 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2565 rt_mask |= (1u << i);
2567 while (i < gl_info->limits.buffers)
2569 context->blit_targets[i] = NULL;
2570 ++i;
2572 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2573 wined3d_rendertarget_view_get_surface(dsv),
2574 rt_count ? rts[0]->resource->draw_binding : 0,
2575 dsv ? dsv->resource->draw_binding : 0);
2577 else
2579 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2580 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2581 rt_mask = context_generate_rt_mask_from_resource(rts[0]->resource);
2584 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2585 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2586 * state management allows this */
2587 context_invalidate_state(context, STATE_FRAMEBUFFER);
2589 else
2591 rt_mask = context_generate_rt_mask_no_fbo(context,
2592 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
2595 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2596 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
2598 for (i = 0; i < rt_count; ++i)
2600 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2601 rt_mask |= (1u << i);
2604 else
2606 rt_mask = context_generate_rt_mask_no_fbo(context,
2607 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
2610 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2612 if (rt_mask != *cur_mask)
2614 context_apply_draw_buffers(context, rt_mask);
2615 *cur_mask = rt_mask;
2616 context_invalidate_state(context, STATE_FRAMEBUFFER);
2619 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2621 context_check_fbo_status(context, GL_FRAMEBUFFER);
2624 if (context->last_was_blit)
2625 context->last_was_blit = FALSE;
2627 /* Blending and clearing should be orthogonal, but tests on the nvidia
2628 * driver show that disabling blending when clearing improves the clearing
2629 * performance incredibly. */
2630 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2631 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2632 if (rt_count && gl_info->supported[ARB_FRAMEBUFFER_SRGB])
2634 if (needs_srgb_write(context, state, fb))
2635 gl_info->gl_ops.gl.p_glEnable(GL_FRAMEBUFFER_SRGB);
2636 else
2637 gl_info->gl_ops.gl.p_glDisable(GL_FRAMEBUFFER_SRGB);
2638 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2640 checkGLcall("setting up state for clear");
2642 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2643 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2644 context_invalidate_state(context, STATE_SCISSORRECT);
2646 return TRUE;
2649 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_state *state)
2651 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
2652 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2653 DWORD rt_mask, rt_mask_bits;
2654 unsigned int i;
2656 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2657 return context_generate_rt_mask_no_fbo(context, wined3d_rendertarget_view_get_surface(rts[0])->container);
2658 else if (!context->render_offscreen)
2659 return context_generate_rt_mask_from_resource(rts[0]->resource);
2661 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2662 rt_mask &= context->d3d_info->valid_rt_mask;
2663 rt_mask_bits = rt_mask;
2664 i = 0;
2665 while (rt_mask_bits)
2667 rt_mask_bits &= ~(1u << i);
2668 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
2669 rt_mask &= ~(1u << i);
2671 i++;
2674 return rt_mask;
2677 /* Context activation is done by the caller. */
2678 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2680 DWORD rt_mask = find_draw_buffers_mask(context, state);
2681 const struct wined3d_fb_state *fb = state->fb;
2682 DWORD *cur_mask;
2684 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2686 if (!context->render_offscreen)
2688 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2689 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2691 else
2693 unsigned int i;
2695 for (i = 0; i < context->gl_info->limits.buffers; ++i)
2697 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(fb->render_targets[i]);
2699 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2700 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
2701 fb->render_targets[0] ? fb->render_targets[0]->resource->draw_binding : 0,
2702 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
2706 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2707 if (rt_mask != *cur_mask)
2709 context_apply_draw_buffers(context, rt_mask);
2710 *cur_mask = rt_mask;
2714 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
2716 DWORD i = context->rev_tex_unit_map[unit];
2717 DWORD j = context->tex_unit_map[stage];
2719 TRACE("Mapping stage %u to unit %u.\n", stage, unit);
2720 context->tex_unit_map[stage] = unit;
2721 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2722 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2724 context->rev_tex_unit_map[unit] = stage;
2725 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2726 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2729 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
2731 DWORD i;
2733 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2734 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
2737 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
2738 const struct wined3d_state *state)
2740 UINT i, start, end;
2742 context->fixed_function_usage_map = 0;
2743 for (i = 0; i < MAX_TEXTURES; ++i)
2745 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2746 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2747 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2748 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2749 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2750 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2751 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2752 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2754 /* Not used, and disable higher stages. */
2755 if (color_op == WINED3D_TOP_DISABLE)
2756 break;
2758 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2759 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2760 || ((color_arg3 == WINED3DTA_TEXTURE)
2761 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2762 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2763 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2764 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2765 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2766 context->fixed_function_usage_map |= (1u << i);
2768 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2769 && i < MAX_TEXTURES - 1)
2770 context->fixed_function_usage_map |= (1u << (i + 1));
2773 if (i < context->lowest_disabled_stage)
2775 start = i;
2776 end = context->lowest_disabled_stage;
2778 else
2780 start = context->lowest_disabled_stage;
2781 end = i;
2784 context->lowest_disabled_stage = i;
2785 for (i = start + 1; i < end; ++i)
2787 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
2791 static void context_map_fixed_function_samplers(struct wined3d_context *context,
2792 const struct wined3d_state *state)
2794 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2795 const struct wined3d_gl_info *gl_info = context->gl_info;
2796 unsigned int i, tex;
2797 WORD ffu_map;
2799 context_update_fixed_function_usage_map(context, state);
2801 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2802 return;
2804 ffu_map = context->fixed_function_usage_map;
2806 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
2807 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
2809 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2811 if (!(ffu_map & 1))
2812 continue;
2814 if (context->tex_unit_map[i] != i)
2816 context_map_stage(context, i, i);
2817 context_invalidate_state(context, STATE_SAMPLER(i));
2818 context_invalidate_texture_stage(context, i);
2821 return;
2824 /* Now work out the mapping */
2825 tex = 0;
2826 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2828 if (!(ffu_map & 1))
2829 continue;
2831 if (context->tex_unit_map[i] != tex)
2833 context_map_stage(context, i, tex);
2834 context_invalidate_state(context, STATE_SAMPLER(i));
2835 context_invalidate_texture_stage(context, i);
2838 ++tex;
2842 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
2844 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2845 const struct wined3d_gl_info *gl_info = context->gl_info;
2846 const struct wined3d_shader_resource_info *resource_info =
2847 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2848 unsigned int i;
2850 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2851 return;
2853 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2855 if (resource_info[i].type && context->tex_unit_map[i] != i)
2857 context_map_stage(context, i, i);
2858 context_invalidate_state(context, STATE_SAMPLER(i));
2859 if (i < d3d_info->limits.ffp_blend_stages)
2860 context_invalidate_texture_stage(context, i);
2865 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
2866 const struct wined3d_shader_resource_info *ps_resource_info, DWORD unit)
2868 DWORD current_mapping = context->rev_tex_unit_map[unit];
2870 /* Not currently used */
2871 if (current_mapping == WINED3D_UNMAPPED_STAGE)
2872 return TRUE;
2874 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
2876 /* Used by a fragment sampler */
2878 if (!ps_resource_info)
2880 /* No pixel shader, check fixed function */
2881 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1u << current_mapping));
2884 /* Pixel shader, check the shader's sampler map */
2885 return !ps_resource_info[current_mapping].type;
2888 return TRUE;
2891 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
2893 const struct wined3d_shader_resource_info *vs_resource_info =
2894 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
2895 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
2896 const struct wined3d_gl_info *gl_info = context->gl_info;
2897 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2898 int i;
2900 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2901 return;
2903 /* Note that we only care if a resource is used or not, not the
2904 * resource's specific type. Otherwise we'd need to call
2905 * shader_update_samplers() here for 1.x pixelshaders. */
2906 if (ps)
2907 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2909 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2911 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2912 if (vs_resource_info[i].type)
2914 while (start >= 0)
2916 if (context_unit_free_for_vs(context, ps_resource_info, start))
2918 if (context->tex_unit_map[vsampler_idx] != start)
2920 context_map_stage(context, vsampler_idx, start);
2921 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
2924 --start;
2925 break;
2928 --start;
2930 if (context->tex_unit_map[vsampler_idx] == WINED3D_UNMAPPED_STAGE)
2931 WARN("Couldn't find a free texture unit for vertex sampler %u.\n", i);
2936 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
2938 BOOL vs = use_vs(state);
2939 BOOL ps = use_ps(state);
2941 /* Try to go for a 1:1 mapping of the samplers when possible. Pixel shaders
2942 * need a 1:1 map at the moment.
2943 * When the mapping of a stage is changed, sampler and ALL texture stage
2944 * states have to be reset. */
2946 if (ps)
2947 context_map_psamplers(context, state);
2948 else
2949 context_map_fixed_function_samplers(context, state);
2951 if (vs)
2952 context_map_vsamplers(context, ps, state);
2955 /* Context activation is done by the caller. */
2956 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2958 DWORD rt_mask, *cur_mask;
2960 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2962 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2963 rt_mask = find_draw_buffers_mask(context, state);
2964 if (rt_mask != *cur_mask)
2966 context_apply_draw_buffers(context, rt_mask);
2967 *cur_mask = rt_mask;
2971 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
2973 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
2974 *regnum = WINED3D_FFP_POSITION;
2975 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
2976 *regnum = WINED3D_FFP_BLENDWEIGHT;
2977 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
2978 *regnum = WINED3D_FFP_BLENDINDICES;
2979 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
2980 *regnum = WINED3D_FFP_NORMAL;
2981 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
2982 *regnum = WINED3D_FFP_PSIZE;
2983 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
2984 *regnum = WINED3D_FFP_DIFFUSE;
2985 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
2986 *regnum = WINED3D_FFP_SPECULAR;
2987 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
2988 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
2989 else
2991 FIXME("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
2992 *regnum = ~0U;
2993 return FALSE;
2996 return TRUE;
2999 /* Context activation is done by the caller. */
3000 void context_stream_info_from_declaration(struct wined3d_context *context,
3001 const struct wined3d_state *state, struct wined3d_stream_info *stream_info)
3003 /* We need to deal with frequency data! */
3004 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
3005 BOOL use_vshader = use_vs(state);
3006 BOOL generic_attributes = context->d3d_info->ffp_generic_attributes;
3007 unsigned int i;
3009 stream_info->use_map = 0;
3010 stream_info->swizzle_map = 0;
3011 stream_info->position_transformed = declaration->position_transformed;
3013 /* Translate the declaration into strided data. */
3014 for (i = 0; i < declaration->element_count; ++i)
3016 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
3017 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
3018 BOOL stride_used;
3019 unsigned int idx;
3021 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
3022 element, i + 1, declaration->element_count);
3024 if (!stream->buffer)
3025 continue;
3027 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
3029 if (use_vshader)
3031 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
3033 stride_used = FALSE;
3035 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
3037 /* TODO: Assuming vertexdeclarations are usually used with the
3038 * same or a similar shader, it might be worth it to store the
3039 * last used output slot and try that one first. */
3040 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
3041 element->usage, element->usage_idx, &idx);
3043 else
3045 idx = element->output_slot;
3046 stride_used = TRUE;
3049 else
3051 if (!generic_attributes && !element->ffp_valid)
3053 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
3054 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
3055 stride_used = FALSE;
3057 else
3059 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
3063 if (stride_used)
3065 TRACE("Load %s array %u [usage %s, usage_idx %u, "
3066 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
3067 use_vshader ? "shader": "fixed function", idx,
3068 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
3069 element->offset, stream->stride, debug_d3dformat(element->format->id),
3070 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
3072 stream_info->elements[idx].format = element->format;
3073 stream_info->elements[idx].data.buffer_object = 0;
3074 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
3075 stream_info->elements[idx].stride = stream->stride;
3076 stream_info->elements[idx].stream_idx = element->input_slot;
3077 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
3079 stream_info->elements[idx].divisor = 1;
3081 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
3083 stream_info->elements[idx].divisor = element->instance_data_step_rate;
3084 if (!element->instance_data_step_rate)
3085 FIXME("Instance step rate 0 not implemented.\n");
3087 else
3089 stream_info->elements[idx].divisor = 0;
3092 if (!context->gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3093 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
3095 stream_info->swizzle_map |= 1u << idx;
3097 stream_info->use_map |= 1u << idx;
3102 /* Context activation is done by the caller. */
3103 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
3105 const struct wined3d_gl_info *gl_info = context->gl_info;
3106 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3107 struct wined3d_stream_info *stream_info = &context->stream_info;
3108 DWORD prev_all_vbo = stream_info->all_vbo;
3109 unsigned int i;
3110 WORD map;
3112 context_stream_info_from_declaration(context, state, stream_info);
3114 stream_info->all_vbo = 1;
3115 context->num_buffer_queries = 0;
3116 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
3118 struct wined3d_stream_info_element *element;
3119 struct wined3d_bo_address data;
3120 struct wined3d_buffer *buffer;
3122 if (!(map & 1))
3123 continue;
3125 element = &stream_info->elements[i];
3126 buffer = state->streams[element->stream_idx].buffer;
3128 /* We can't use VBOs if the base vertex index is negative. OpenGL
3129 * doesn't accept negative offsets (or rather offsets bigger than the
3130 * VBO, because the pointer is unsigned), so use system memory
3131 * sources. In most sane cases the pointer - offset will still be > 0,
3132 * otherwise it will wrap around to some big value. Hope that with the
3133 * indices the driver wraps it back internally. If not,
3134 * draw_primitive_immediate_mode() is needed, including a vertex buffer
3135 * path. */
3136 if (state->load_base_vertex_index < 0)
3138 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
3139 state->load_base_vertex_index);
3140 element->data.buffer_object = 0;
3141 element->data.addr += (ULONG_PTR)buffer_get_sysmem(buffer, context);
3142 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
3143 FIXME("System memory vertex data load offset is negative!\n");
3145 else
3147 buffer_internal_preload(buffer, context, state);
3148 buffer_get_memory(buffer, context, &data);
3149 element->data.buffer_object = data.buffer_object;
3150 element->data.addr += (ULONG_PTR)data.addr;
3153 if (!element->data.buffer_object)
3154 stream_info->all_vbo = 0;
3156 if (buffer->query)
3157 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
3159 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
3162 if (use_vs(state))
3164 if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
3166 TRACE("Using immediate mode draw with vertex shaders for FLOAT16 conversion.\n");
3167 context->use_immediate_mode_draw = TRUE;
3169 else
3171 context->use_immediate_mode_draw = FALSE;
3174 else
3176 WORD slow_mask = -!d3d_info->ffp_generic_attributes & (1u << WINED3D_FFP_PSIZE);
3177 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3178 & ((1u << WINED3D_FFP_DIFFUSE) | (1u << WINED3D_FFP_SPECULAR));
3180 if (((stream_info->position_transformed && !d3d_info->xyzrhw)
3181 || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
3182 context->use_immediate_mode_draw = TRUE;
3183 else
3184 context->use_immediate_mode_draw = FALSE;
3187 if (prev_all_vbo != stream_info->all_vbo)
3188 context_invalidate_state(context, STATE_INDEXBUFFER);
3191 /* Context activation is done by the caller. */
3192 static void context_preload_texture(struct wined3d_context *context,
3193 const struct wined3d_state *state, unsigned int idx)
3195 struct wined3d_texture *texture;
3197 if (!(texture = state->textures[idx]))
3198 return;
3200 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3203 /* Context activation is done by the caller. */
3204 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3206 unsigned int i;
3208 if (use_vs(state))
3210 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3212 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3213 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3217 if (use_ps(state))
3219 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3221 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3222 context_preload_texture(context, state, i);
3225 else
3227 WORD ffu_map = context->fixed_function_usage_map;
3229 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3231 if (ffu_map & 1)
3232 context_preload_texture(context, state, i);
3237 static void context_load_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3239 struct wined3d_shader_sampler_map_entry *entry;
3240 struct wined3d_shader_resource_view *view;
3241 struct wined3d_shader *shader;
3242 unsigned int i, j;
3244 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3246 if (!(shader = state->shader[i]))
3247 continue;
3249 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3251 if (state->cb[i][j])
3252 buffer_internal_preload(state->cb[i][j], context, state);
3255 for (j = 0; j < shader->reg_maps.sampler_map.count; ++j)
3257 entry = &shader->reg_maps.sampler_map.entries[j];
3259 if (!(view = state->shader_resource_view[i][entry->resource_idx]))
3261 WARN("No resource view bound at index %u, %u.\n", i, entry->resource_idx);
3262 continue;
3265 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3266 buffer_internal_preload(buffer_from_resource(view->resource), context, state);
3267 else
3268 wined3d_texture_load(texture_from_resource(view->resource), context, FALSE);
3273 static void context_bind_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3275 const struct wined3d_device *device = context->swapchain->device;
3276 const struct wined3d_gl_info *gl_info = context->gl_info;
3277 struct wined3d_shader_sampler_map_entry *entry;
3278 struct wined3d_shader_resource_view *view;
3279 struct wined3d_sampler *sampler;
3280 struct wined3d_texture *texture;
3281 struct wined3d_shader *shader;
3282 unsigned int i, j, count;
3283 GLuint sampler_name;
3285 static const struct
3287 enum wined3d_shader_type type;
3288 unsigned int base_idx;
3289 unsigned int count;
3291 shader_types[] =
3293 {WINED3D_SHADER_TYPE_PIXEL, 0, MAX_FRAGMENT_SAMPLERS},
3294 {WINED3D_SHADER_TYPE_VERTEX, MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS},
3297 for (i = 0; i < ARRAY_SIZE(shader_types); ++i)
3299 if (!(shader = state->shader[shader_types[i].type]))
3300 continue;
3302 count = shader->reg_maps.sampler_map.count;
3303 if (count > shader_types[i].count)
3305 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3306 shader, count, shader_types[i].count);
3307 count = shader_types[i].count;
3310 for (j = 0; j < count; ++j)
3312 entry = &shader->reg_maps.sampler_map.entries[j];
3314 if (!(view = state->shader_resource_view[shader_types[i].type][entry->resource_idx]))
3316 WARN("No resource view bound at index %u, %u.\n", shader_types[i].type, entry->resource_idx);
3317 continue;
3320 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3322 FIXME("Buffer shader resources not supported.\n");
3323 continue;
3326 if (entry->sampler_idx == WINED3D_SAMPLER_DEFAULT)
3328 sampler_name = device->default_sampler;
3330 else if ((sampler = state->sampler[shader_types[i].type][entry->sampler_idx]))
3332 sampler_name = sampler->name;
3334 else
3336 WARN("No sampler object bound at index %u, %u.\n", shader_types[i].type, entry->sampler_idx);
3337 continue;
3340 texture = texture_from_resource(view->resource);
3341 context_active_texture(context, gl_info, shader_types[i].base_idx + entry->bind_idx);
3342 wined3d_texture_bind(texture, context, FALSE);
3344 GL_EXTCALL(glBindSampler(shader_types[i].base_idx + entry->bind_idx, sampler_name));
3345 checkGLcall("glBindSampler");
3350 /* Context activation is done by the caller. */
3351 BOOL context_apply_draw_state(struct wined3d_context *context,
3352 const struct wined3d_device *device, const struct wined3d_state *state)
3354 const struct StateEntry *state_table = context->state_table;
3355 const struct wined3d_fb_state *fb = state->fb;
3356 unsigned int i;
3357 WORD map;
3359 if (!context_validate_rt_config(context->gl_info->limits.buffers,
3360 fb->render_targets, fb->depth_stencil))
3361 return FALSE;
3363 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3365 context_validate_onscreen_formats(context, fb->depth_stencil);
3368 /* Preload resources before FBO setup. Texture preload in particular may
3369 * result in changes to the current FBO, due to using e.g. FBO blits for
3370 * updating a resource location. */
3371 context_update_tex_unit_map(context, state);
3372 context_preload_textures(context, state);
3373 context_load_shader_resources(context, state);
3374 /* TODO: Right now the dependency on the vertex shader is necessary
3375 * since context_stream_info_from_declaration depends on the reg_maps of
3376 * the current VS but maybe it's possible to relax the coupling in some
3377 * situations at least. */
3378 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3379 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3381 context_update_stream_info(context, state);
3383 else
3385 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3387 if (map & 1)
3388 buffer_mark_used(state->streams[context->stream_info.elements[i].stream_idx].buffer);
3391 if (state->index_buffer)
3393 if (context->stream_info.all_vbo)
3394 buffer_internal_preload(state->index_buffer, context, state);
3395 else
3396 buffer_get_sysmem(state->index_buffer, context);
3399 for (i = 0; i < context->numDirtyEntries; ++i)
3401 DWORD rep = context->dirtyArray[i];
3402 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3403 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3404 context->isStateDirty[idx] &= ~(1u << shift);
3405 state_table[rep].apply(context, state, rep);
3408 if (context->shader_update_mask)
3410 device->shader_backend->shader_select(device->shader_priv, context, state);
3411 context->shader_update_mask = 0;
3414 if (context->constant_update_mask)
3416 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3417 context->constant_update_mask = 0;
3420 if (context->update_shader_resource_bindings)
3422 context_bind_shader_resources(context, state);
3423 context->update_shader_resource_bindings = 0;
3426 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3428 context_check_fbo_status(context, GL_FRAMEBUFFER);
3431 context->numDirtyEntries = 0; /* This makes the whole list clean */
3432 context->last_was_blit = FALSE;
3434 return TRUE;
3437 static void context_setup_target(struct wined3d_context *context,
3438 struct wined3d_texture *texture, unsigned int sub_resource_idx)
3440 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
3442 render_offscreen = wined3d_resource_is_offscreen(&texture->resource);
3443 if (context->current_rt.texture == texture
3444 && context->current_rt.sub_resource_idx == sub_resource_idx
3445 && render_offscreen == old_render_offscreen)
3446 return;
3448 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
3449 * the alpha blend state changes with different render target formats. */
3450 if (!context->current_rt.texture)
3452 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3454 else
3456 const struct wined3d_format *old = context->current_rt.texture->resource.format;
3457 const struct wined3d_format *new = texture->resource.format;
3459 if (old->id != new->id)
3461 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
3462 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
3463 || !(texture->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
3464 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3466 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
3467 if ((context->current_rt.texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
3468 != (texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
3469 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3472 /* When switching away from an offscreen render target, and we're not
3473 * using FBOs, we have to read the drawable into the texture. This is
3474 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
3475 * There are some things that need care though. PreLoad needs a GL context,
3476 * and FindContext is called before the context is activated. It also
3477 * has to be called with the old rendertarget active, otherwise a
3478 * wrong drawable is read. */
3479 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
3480 && old_render_offscreen && (context->current_rt.texture != texture
3481 || context->current_rt.sub_resource_idx != sub_resource_idx))
3483 unsigned int prev_sub_resource_idx = context->current_rt.sub_resource_idx;
3484 struct wined3d_texture *prev_texture = context->current_rt.texture;
3486 /* Read the back buffer of the old drawable into the destination texture. */
3487 if (prev_texture->texture_srgb.name)
3488 wined3d_texture_load(prev_texture, context, TRUE);
3489 wined3d_texture_load(prev_texture, context, FALSE);
3490 wined3d_texture_invalidate_location(prev_texture, prev_sub_resource_idx, WINED3D_LOCATION_DRAWABLE);
3494 context->current_rt.texture = texture;
3495 context->current_rt.sub_resource_idx = sub_resource_idx;
3496 context_set_render_offscreen(context, render_offscreen);
3499 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
3501 struct wined3d_context *current_context = context_get_current();
3502 struct wined3d_texture *target_texture;
3503 unsigned int target_sub_resource_idx;
3504 struct wined3d_context *context;
3506 TRACE("device %p, target %p.\n", device, target);
3508 if (current_context && current_context->destroyed)
3509 current_context = NULL;
3511 if (target)
3513 target_texture = target->container;
3514 target_sub_resource_idx = surface_get_sub_resource_idx(target);
3516 else
3518 if (current_context
3519 && current_context->current_rt.texture
3520 && current_context->swapchain->device == device)
3522 target_texture = current_context->current_rt.texture;
3523 target_sub_resource_idx = current_context->current_rt.sub_resource_idx;
3525 else
3527 struct wined3d_swapchain *swapchain = device->swapchains[0];
3529 if (swapchain->back_buffers)
3530 target_texture = swapchain->back_buffers[0];
3531 else
3532 target_texture = swapchain->front_buffer;
3533 target_sub_resource_idx = 0;
3537 if (current_context && current_context->current_rt.texture == target_texture)
3539 context = current_context;
3541 else if (target_texture->swapchain)
3543 TRACE("Rendering onscreen.\n");
3545 context = swapchain_get_context(target_texture->swapchain);
3547 else
3549 TRACE("Rendering offscreen.\n");
3551 /* Stay with the current context if possible. Otherwise use the
3552 * context for the primary swapchain. */
3553 if (current_context && current_context->swapchain->device == device)
3554 context = current_context;
3555 else
3556 context = swapchain_get_context(device->swapchains[0]);
3559 context_enter(context);
3560 context_update_window(context);
3561 context_setup_target(context, target_texture, target_sub_resource_idx);
3562 if (!context->valid) return context;
3564 if (context != current_context)
3566 if (!context_set_current(context))
3567 ERR("Failed to activate the new context.\n");
3569 else if (context->needs_set)
3571 context_set_gl_context(context);
3574 return context;