d3d8/tests: Add a system memory miptree layout test.
[wine.git] / dlls / wined3d / context.c
blobd68332786090c503c65222f36281a161e20e0d20
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 /* Context activation is done by the caller. */
122 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
123 GLenum fbo_target, const struct wined3d_fbo_resource *resource, BOOL rb_namespace,
124 DWORD flags)
126 const struct wined3d_gl_info *gl_info = context->gl_info;
128 if (resource->object)
130 TRACE("Attach depth stencil %u.\n", resource->object);
132 if (rb_namespace)
134 context_attach_depth_stencil_rb(gl_info, fbo_target,
135 flags, resource->object);
137 else
139 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
141 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
142 resource->target, resource->object, resource->level);
143 checkGLcall("glFramebufferTexture2D()");
146 if (flags & WINED3D_FBO_ENTRY_FLAG_STENCIL)
148 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
149 resource->target, resource->object, resource->level);
150 checkGLcall("glFramebufferTexture2D()");
154 if (!(flags & WINED3D_FBO_ENTRY_FLAG_DEPTH))
156 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
157 checkGLcall("glFramebufferTexture2D()");
160 if (!(flags & WINED3D_FBO_ENTRY_FLAG_STENCIL))
162 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
163 checkGLcall("glFramebufferTexture2D()");
166 else
168 TRACE("Attach depth stencil 0.\n");
170 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
171 checkGLcall("glFramebufferTexture2D()");
173 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
174 checkGLcall("glFramebufferTexture2D()");
178 /* Context activation is done by the caller. */
179 static void context_attach_surface_fbo(struct wined3d_context *context,
180 GLenum fbo_target, DWORD idx, const struct wined3d_fbo_resource *resource, BOOL rb_namespace)
182 const struct wined3d_gl_info *gl_info = context->gl_info;
184 TRACE("Attach GL object %u to %u.\n", resource->object, idx);
186 if (resource->object)
189 if (rb_namespace)
191 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
192 GL_RENDERBUFFER, resource->object);
193 checkGLcall("glFramebufferRenderbuffer()");
195 else
197 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
198 resource->target, resource->object, resource->level);
199 checkGLcall("glFramebufferTexture2D()");
202 else
204 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
205 checkGLcall("glFramebufferTexture2D()");
209 static void context_dump_fbo_attachment(const struct wined3d_gl_info *gl_info, GLenum target,
210 GLenum attachment)
212 GLint type, name, samples, width, height, old_texture, level, face, fmt, tex_target;
214 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
215 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &name);
216 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
217 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);
219 if (type == GL_RENDERBUFFER)
221 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, name);
222 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
223 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
224 if (gl_info->limits.samples > 1)
225 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
226 else
227 samples = 1;
228 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &fmt);
229 FIXME(" %s: renderbuffer %d, %dx%d, %d samples, format %#x.\n",
230 debug_fboattachment(attachment), name, width, height, samples, fmt);
232 else if (type == GL_TEXTURE)
234 const char *tex_type_str;
236 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
237 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &level);
238 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
239 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, &face);
241 if (face)
243 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &old_texture);
245 glBindTexture(GL_TEXTURE_CUBE_MAP, name);
246 glGetTexLevelParameteriv(face, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
247 glGetTexLevelParameteriv(face, level, GL_TEXTURE_WIDTH, &width);
248 glGetTexLevelParameteriv(face, level, GL_TEXTURE_HEIGHT, &height);
250 tex_target = GL_TEXTURE_CUBE_MAP;
251 tex_type_str = "cube";
253 else
255 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_texture);
256 while (gl_info->gl_ops.gl.p_glGetError());
258 glBindTexture(GL_TEXTURE_2D, name);
259 if (!gl_info->gl_ops.gl.p_glGetError())
261 tex_target = GL_TEXTURE_2D;
262 tex_type_str = "2d";
264 else
266 glBindTexture(GL_TEXTURE_2D, old_texture);
267 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_texture);
269 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, name);
270 if (gl_info->gl_ops.gl.p_glGetError())
272 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, old_texture);
273 FIXME("Cannot find type of texture %d.\n", name);
274 return;
276 tex_target = GL_TEXTURE_RECTANGLE_ARB;
277 tex_type_str = "rectangle";
280 glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
281 glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_WIDTH, &width);
282 glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_HEIGHT, &height);
285 FIXME(" %s: %s texture %d, %dx%d, format %#x.\n", debug_fboattachment(attachment),
286 tex_type_str, name, width, height, fmt);
288 glBindTexture(tex_target, old_texture);
290 else if (type == GL_NONE)
292 FIXME("\t%s: NONE.\n", debug_fboattachment(attachment));
294 else
295 ERR("\t%s: Unknown attachment %#x.\n", debug_fboattachment(attachment), type);
298 /* Context activation is done by the caller. */
299 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
301 const struct wined3d_gl_info *gl_info = context->gl_info;
302 GLenum status;
304 if (!FIXME_ON(d3d)) return;
306 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
307 if (status == GL_FRAMEBUFFER_COMPLETE)
309 TRACE("FBO complete\n");
311 else
313 unsigned int i;
315 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
317 if (!context->current_fbo)
319 ERR("FBO 0 is incomplete, driver bug?\n");
320 return;
323 context_dump_fbo_attachment(gl_info, target, GL_DEPTH_ATTACHMENT);
324 context_dump_fbo_attachment(gl_info, target, GL_STENCIL_ATTACHMENT);
326 for (i = 0; i < gl_info->limits.buffers; ++i)
327 context_dump_fbo_attachment(gl_info, target, GL_COLOR_ATTACHMENT0 + i);
328 checkGLcall("Dump FBO attachments");
332 static inline DWORD context_generate_rt_mask(GLenum buffer)
334 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
335 return buffer ? (1u << 31) | buffer : 0;
338 static inline DWORD context_generate_rt_mask_from_resource(struct wined3d_resource *resource)
340 if (resource->type != WINED3D_RTYPE_TEXTURE_2D)
342 FIXME("Not implemented for %s resources.\n", debug_d3dresourcetype(resource->type));
343 return 0;
346 return (1u << 31) | wined3d_texture_get_gl_buffer(wined3d_texture_from_resource(resource));
349 static inline void context_set_fbo_key_for_surface(const struct wined3d_context *context,
350 struct wined3d_fbo_entry_key *key, UINT idx, struct wined3d_surface *surface,
351 DWORD location)
353 if (!surface)
355 key->objects[idx].object = 0;
356 key->objects[idx].level = key->objects[idx].target = 0;
358 else if (surface->current_renderbuffer)
360 key->objects[idx].object = surface->current_renderbuffer->id;
361 key->objects[idx].level = key->objects[idx].target = 0;
362 key->rb_namespace |= 1 << idx;
364 else
366 switch (location)
368 case WINED3D_LOCATION_TEXTURE_RGB:
369 key->objects[idx].object = surface_get_texture_name(surface, context, FALSE);
370 key->objects[idx].level = surface->texture_level;
371 key->objects[idx].target = surface->texture_target;
372 break;
374 case WINED3D_LOCATION_TEXTURE_SRGB:
375 key->objects[idx].object = surface_get_texture_name(surface, context, TRUE);
376 key->objects[idx].level = surface->texture_level;
377 key->objects[idx].target = surface->texture_target;
378 break;
380 case WINED3D_LOCATION_RB_MULTISAMPLE:
381 key->objects[idx].object = surface->rb_multisample;
382 key->objects[idx].level = key->objects[idx].target = 0;
383 key->rb_namespace |= 1 << idx;
384 break;
386 case WINED3D_LOCATION_RB_RESOLVED:
387 key->objects[idx].object = surface->rb_resolved;
388 key->objects[idx].level = key->objects[idx].target = 0;
389 key->rb_namespace |= 1 << idx;
390 break;
395 static void context_generate_fbo_key(const struct wined3d_context *context,
396 struct wined3d_fbo_entry_key *key, struct wined3d_surface **render_targets,
397 struct wined3d_surface *depth_stencil, DWORD color_location,
398 DWORD ds_location)
400 UINT i;
402 key->rb_namespace = 0;
403 context_set_fbo_key_for_surface(context, key, 0, depth_stencil, ds_location);
405 for (i = 0; i < context->gl_info->limits.buffers; ++i)
406 context_set_fbo_key_for_surface(context, key, i + 1, render_targets[i], color_location);
409 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
410 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
411 DWORD color_location, DWORD ds_location)
413 const struct wined3d_gl_info *gl_info = context->gl_info;
414 struct fbo_entry *entry;
415 UINT object_count = gl_info->limits.buffers + 1;
417 entry = HeapAlloc(GetProcessHeap(), 0,
418 FIELD_OFFSET(struct fbo_entry, key.objects[object_count]));
419 memset(&entry->key, 0, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count]));
420 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
421 entry->flags = 0;
422 if (depth_stencil)
424 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
425 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
426 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
427 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
429 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
430 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
431 checkGLcall("glGenFramebuffers()");
432 TRACE("Created FBO %u.\n", entry->id);
434 return entry;
437 /* Context activation is done by the caller. */
438 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
439 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
440 DWORD color_location, DWORD ds_location, struct fbo_entry *entry)
442 const struct wined3d_gl_info *gl_info = context->gl_info;
444 context_bind_fbo(context, target, entry->id);
445 context_clean_fbo_attachments(gl_info, target);
447 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
448 entry->flags = 0;
449 if (depth_stencil)
451 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
452 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
453 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
454 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
458 /* Context activation is done by the caller. */
459 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
461 if (entry->id)
463 TRACE("Destroy FBO %u.\n", entry->id);
464 context_destroy_fbo(context, entry->id);
466 --context->fbo_entry_count;
467 list_remove(&entry->entry);
468 HeapFree(GetProcessHeap(), 0, entry);
471 /* Context activation is done by the caller. */
472 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
473 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
474 DWORD color_location, DWORD ds_location)
476 const struct wined3d_gl_info *gl_info = context->gl_info;
477 struct fbo_entry *entry;
478 UINT object_count = gl_info->limits.buffers + 1;
479 unsigned int i;
481 if (depth_stencil && render_targets[0])
483 if (wined3d_texture_get_level_width(depth_stencil->container, depth_stencil->texture_level)
484 < wined3d_texture_get_level_width(render_targets[0]->container, render_targets[0]->texture_level)
485 || wined3d_texture_get_level_height(depth_stencil->container, depth_stencil->texture_level)
486 < wined3d_texture_get_level_height(render_targets[0]->container, render_targets[0]->texture_level))
488 WARN("Depth stencil is smaller than the primary color buffer, disabling\n");
489 depth_stencil = NULL;
491 else if (depth_stencil->container->resource.multisample_type
492 != render_targets[0]->container->resource.multisample_type
493 || depth_stencil->container->resource.multisample_quality
494 != render_targets[0]->container->resource.multisample_quality)
496 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
497 render_targets[0]->container->resource.multisample_type,
498 render_targets[0]->container->resource.multisample_quality,
499 depth_stencil->container->resource.multisample_type,
500 depth_stencil->container->resource.multisample_quality);
501 depth_stencil = NULL;
503 else
504 surface_set_compatible_renderbuffer(depth_stencil, render_targets[0]);
507 context_generate_fbo_key(context, context->fbo_key, render_targets, depth_stencil, color_location,
508 ds_location);
510 if (TRACE_ON(d3d))
512 TRACE("Dumping FBO attachments:\n");
513 for (i = 0; i < gl_info->limits.buffers; ++i)
515 if (render_targets[i])
517 TRACE(" Color attachment %u: (%p) %s gl obj %u(%s) %ux%u %u samples.\n",
518 i, render_targets[i], debug_d3dformat(render_targets[i]->container->resource.format->id),
519 context->fbo_key->objects[i + 1].object,
520 context->fbo_key->rb_namespace & (1 << (i + 1)) ? "rb" : "texure",
521 render_targets[i]->pow2Width, render_targets[i]->pow2Height,
522 render_targets[i]->container->resource.multisample_type);
525 if (depth_stencil)
527 TRACE(" Depth attachment: (%p) %s gl obj %u(%s) %ux%u %u samples.\n",
528 depth_stencil, debug_d3dformat(depth_stencil->container->resource.format->id),
529 context->fbo_key->objects[0].object,
530 context->fbo_key->rb_namespace & (1 << 0) ? "rb" : "texure",
531 depth_stencil->pow2Width, depth_stencil->pow2Height,
532 depth_stencil->container->resource.multisample_type);
536 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
538 if (memcmp(context->fbo_key, &entry->key, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count])))
539 continue;
541 list_remove(&entry->entry);
542 list_add_head(&context->fbo_list, &entry->entry);
543 return entry;
546 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
548 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
549 list_add_head(&context->fbo_list, &entry->entry);
550 ++context->fbo_entry_count;
552 else
554 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
555 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
556 list_remove(&entry->entry);
557 list_add_head(&context->fbo_list, &entry->entry);
560 return entry;
563 /* Context activation is done by the caller. */
564 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
566 const struct wined3d_gl_info *gl_info = context->gl_info;
567 unsigned int i;
568 GLuint read_binding, draw_binding;
570 if (entry->flags & WINED3D_FBO_ENTRY_FLAG_ATTACHED)
572 context_bind_fbo(context, target, entry->id);
573 return;
576 read_binding = context->fbo_read_binding;
577 draw_binding = context->fbo_draw_binding;
578 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
580 /* Apply render targets */
581 for (i = 0; i < gl_info->limits.buffers; ++i)
583 context_attach_surface_fbo(context, target, i, &entry->key.objects[i + 1],
584 entry->key.rb_namespace & (1 << (i + 1)));
587 context_attach_depth_stencil_fbo(context, target, &entry->key.objects[0],
588 entry->key.rb_namespace & 0x1, entry->flags);
590 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
591 * GL contexts requirements. */
592 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
593 context_set_draw_buffer(context, GL_NONE);
594 if (target != GL_FRAMEBUFFER)
596 if (target == GL_READ_FRAMEBUFFER)
597 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
598 else
599 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
602 entry->flags |= WINED3D_FBO_ENTRY_FLAG_ATTACHED;
605 /* Context activation is done by the caller. */
606 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
607 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
608 DWORD color_location, DWORD ds_location)
610 struct fbo_entry *entry, *entry2;
612 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
614 context_destroy_fbo_entry(context, entry);
617 if (context->rebind_fbo)
619 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
620 context->rebind_fbo = FALSE;
623 if (color_location == WINED3D_LOCATION_DRAWABLE)
625 context->current_fbo = NULL;
626 context_bind_fbo(context, target, 0);
628 else
630 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
631 color_location, ds_location);
632 context_apply_fbo_entry(context, target, context->current_fbo);
636 /* Context activation is done by the caller. */
637 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
638 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
640 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
642 context->blit_targets[0] = render_target;
643 if (clear_size)
644 memset(&context->blit_targets[1], 0, clear_size);
645 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
648 /* Context activation is done by the caller. */
649 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
651 const struct wined3d_gl_info *gl_info = context->gl_info;
653 if (context->free_occlusion_query_count)
655 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
657 else
659 if (gl_info->supported[ARB_OCCLUSION_QUERY])
661 GL_EXTCALL(glGenQueries(1, &query->id));
662 checkGLcall("glGenQueries");
664 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
666 else
668 WARN("Occlusion queries not supported, not allocating query id.\n");
669 query->id = 0;
673 query->context = context;
674 list_add_head(&context->occlusion_queries, &query->entry);
677 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
679 struct wined3d_context *context = query->context;
681 list_remove(&query->entry);
682 query->context = NULL;
684 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
686 UINT new_size = context->free_occlusion_query_size << 1;
687 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
688 new_size * sizeof(*context->free_occlusion_queries));
690 if (!new_data)
692 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
693 return;
696 context->free_occlusion_query_size = new_size;
697 context->free_occlusion_queries = new_data;
700 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
703 /* Context activation is done by the caller. */
704 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
706 const struct wined3d_gl_info *gl_info = context->gl_info;
708 if (context->free_event_query_count)
710 query->object = context->free_event_queries[--context->free_event_query_count];
712 else
714 if (gl_info->supported[ARB_SYNC])
716 /* Using ARB_sync, not much to do here. */
717 query->object.sync = NULL;
718 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
720 else if (gl_info->supported[APPLE_FENCE])
722 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
723 checkGLcall("glGenFencesAPPLE");
725 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
727 else if(gl_info->supported[NV_FENCE])
729 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
730 checkGLcall("glGenFencesNV");
732 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
734 else
736 WARN("Event queries not supported, not allocating query id.\n");
737 query->object.id = 0;
741 query->context = context;
742 list_add_head(&context->event_queries, &query->entry);
745 void context_free_event_query(struct wined3d_event_query *query)
747 struct wined3d_context *context = query->context;
749 list_remove(&query->entry);
750 query->context = NULL;
752 if (context->free_event_query_count >= context->free_event_query_size - 1)
754 UINT new_size = context->free_event_query_size << 1;
755 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
756 new_size * sizeof(*context->free_event_queries));
758 if (!new_data)
760 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
761 return;
764 context->free_event_query_size = new_size;
765 context->free_event_queries = new_data;
768 context->free_event_queries[context->free_event_query_count++] = query->object;
771 /* Context activation is done by the caller. */
772 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
774 const struct wined3d_gl_info *gl_info = context->gl_info;
776 if (context->free_timestamp_query_count)
778 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
780 else
782 GL_EXTCALL(glGenQueries(1, &query->id));
783 checkGLcall("glGenQueries");
785 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
788 query->context = context;
789 list_add_head(&context->timestamp_queries, &query->entry);
792 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
794 struct wined3d_context *context = query->context;
796 list_remove(&query->entry);
797 query->context = NULL;
799 if (context->free_timestamp_query_count >= context->free_timestamp_query_size - 1)
801 UINT new_size = context->free_timestamp_query_size << 1;
802 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_timestamp_queries,
803 new_size * sizeof(*context->free_timestamp_queries));
805 if (!new_data)
807 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
808 return;
811 context->free_timestamp_query_size = new_size;
812 context->free_timestamp_queries = new_data;
815 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
818 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
820 static void context_enum_fbo_entries(const struct wined3d_device *device,
821 GLuint name, BOOL rb_namespace, context_fbo_entry_func_t *callback)
823 UINT i;
825 for (i = 0; i < device->context_count; ++i)
827 struct wined3d_context *context = device->contexts[i];
828 const struct wined3d_gl_info *gl_info = context->gl_info;
829 struct fbo_entry *entry, *entry2;
831 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
833 UINT j;
835 for (j = 0; j < gl_info->limits.buffers + 1; ++j)
837 if (entry->key.objects[j].object == name
838 && !(entry->key.rb_namespace & (1 << j)) == !rb_namespace)
840 callback(context, entry);
841 break;
848 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
850 list_remove(&entry->entry);
851 list_add_head(&context->fbo_destroy_list, &entry->entry);
854 void context_resource_released(const struct wined3d_device *device,
855 struct wined3d_resource *resource, enum wined3d_resource_type type)
857 struct wined3d_texture *texture;
858 UINT i;
860 if (!device->d3d_initialized)
861 return;
863 switch (type)
865 case WINED3D_RTYPE_TEXTURE_2D:
866 case WINED3D_RTYPE_TEXTURE_3D:
867 texture = wined3d_texture_from_resource(resource);
869 for (i = 0; i < device->context_count; ++i)
871 struct wined3d_context *context = device->contexts[i];
872 if (context->current_rt.texture == texture)
874 context->current_rt.texture = NULL;
875 context->current_rt.sub_resource_idx = 0;
878 break;
880 default:
881 break;
885 void context_gl_resource_released(struct wined3d_device *device,
886 GLuint name, BOOL rb_namespace)
888 context_enum_fbo_entries(device, name, rb_namespace, context_queue_fbo_entry_destruction);
891 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
893 const struct wined3d_gl_info *gl_info = context->gl_info;
894 struct fbo_entry *entry = context->current_fbo;
895 unsigned int i;
897 if (!entry || context->rebind_fbo) return;
899 for (i = 0; i < gl_info->limits.buffers + 1; ++i)
901 if (surface->container->texture_rgb.name == entry->key.objects[i].object
902 || surface->container->texture_srgb.name == entry->key.objects[i].object)
904 TRACE("Updated surface %p is bound as attachment %u to the current FBO.\n", surface, i);
905 context->rebind_fbo = TRUE;
906 return;
911 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
913 const struct wined3d_gl_info *gl_info = ctx->gl_info;
914 BOOL ret = FALSE;
916 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
918 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
920 HDC dc = GetDCEx(ctx->restore_pf_win, 0, DCX_USESTYLE | DCX_CACHE);
921 if (dc)
923 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
925 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
926 ctx->restore_pf, ctx->restore_pf_win);
928 ReleaseDC(ctx->restore_pf_win, dc);
931 else
933 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
937 ctx->restore_pf = 0;
938 ctx->restore_pf_win = NULL;
939 return ret;
942 static BOOL context_set_pixel_format(struct wined3d_context *context, HDC dc, BOOL private, int format)
944 const struct wined3d_gl_info *gl_info = context->gl_info;
945 int current;
947 if (dc == context->hdc && context->hdc_is_private && context->hdc_has_format)
948 return TRUE;
950 current = gl_info->gl_ops.wgl.p_wglGetPixelFormat(dc);
951 if (current == format) goto success;
953 if (!current)
955 if (!SetPixelFormat(dc, format, NULL))
957 /* This may also happen if the dc belongs to a destroyed window. */
958 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
959 format, dc, GetLastError());
960 return FALSE;
963 context->restore_pf = 0;
964 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
965 goto success;
968 /* By default WGL doesn't allow pixel format adjustments but we need it
969 * here. For this reason there's a Wine specific wglSetPixelFormat()
970 * which allows us to set the pixel format multiple times. Only use it
971 * when really needed. */
972 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
974 HWND win;
976 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
978 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
979 format, dc);
980 return FALSE;
983 win = private ? NULL : WindowFromDC(dc);
984 if (win != context->restore_pf_win)
986 context_restore_pixel_format(context);
988 context->restore_pf = private ? 0 : current;
989 context->restore_pf_win = win;
992 goto success;
995 /* OpenGL doesn't allow pixel format adjustments. Print an error and
996 * continue using the old format. There's a big chance that the old
997 * format works although with a performance hit and perhaps rendering
998 * errors. */
999 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
1000 format, dc, current);
1001 return TRUE;
1003 success:
1004 if (dc == context->hdc && context->hdc_is_private)
1005 context->hdc_has_format = TRUE;
1006 return TRUE;
1009 static BOOL context_set_gl_context(struct wined3d_context *ctx)
1011 struct wined3d_swapchain *swapchain = ctx->swapchain;
1012 BOOL backup = FALSE;
1014 if (!context_set_pixel_format(ctx, ctx->hdc, ctx->hdc_is_private, ctx->pixel_format))
1016 WARN("Failed to set pixel format %d on device context %p.\n",
1017 ctx->pixel_format, ctx->hdc);
1018 backup = TRUE;
1021 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
1023 HDC dc;
1025 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
1026 ctx->glCtx, ctx->hdc, GetLastError());
1027 ctx->valid = 0;
1028 WARN("Trying fallback to the backup window.\n");
1030 /* FIXME: If the context is destroyed it's no longer associated with
1031 * a swapchain, so we can't use the swapchain to get a backup dc. To
1032 * make this work windowless contexts would need to be handled by the
1033 * device. */
1034 if (ctx->destroyed)
1036 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
1037 context_set_current(NULL);
1038 return FALSE;
1041 if (!(dc = swapchain_get_backup_dc(swapchain)))
1043 context_set_current(NULL);
1044 return FALSE;
1047 if (!context_set_pixel_format(ctx, dc, TRUE, ctx->pixel_format))
1049 ERR("Failed to set pixel format %d on device context %p.\n",
1050 ctx->pixel_format, dc);
1051 context_set_current(NULL);
1052 return FALSE;
1055 if (!wglMakeCurrent(dc, ctx->glCtx))
1057 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
1058 dc, GetLastError());
1059 context_set_current(NULL);
1060 return FALSE;
1063 ctx->valid = 1;
1065 ctx->needs_set = 0;
1066 return TRUE;
1069 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
1071 if (!wglMakeCurrent(dc, gl_ctx))
1073 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1074 gl_ctx, dc, GetLastError());
1075 context_set_current(NULL);
1079 static void context_update_window(struct wined3d_context *context)
1081 if (context->win_handle == context->swapchain->win_handle)
1082 return;
1084 TRACE("Updating context %p window from %p to %p.\n",
1085 context, context->win_handle, context->swapchain->win_handle);
1087 if (context->hdc)
1088 wined3d_release_dc(context->win_handle, context->hdc);
1090 context->win_handle = context->swapchain->win_handle;
1091 context->hdc_is_private = FALSE;
1092 context->hdc_has_format = FALSE;
1093 context->needs_set = 1;
1094 context->valid = 1;
1096 if (!(context->hdc = GetDCEx(context->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1098 ERR("Failed to get a device context for window %p.\n", context->win_handle);
1099 context->valid = 0;
1103 static void context_destroy_gl_resources(struct wined3d_context *context)
1105 const struct wined3d_gl_info *gl_info = context->gl_info;
1106 struct wined3d_timestamp_query *timestamp_query;
1107 struct wined3d_occlusion_query *occlusion_query;
1108 struct wined3d_event_query *event_query;
1109 struct fbo_entry *entry, *entry2;
1110 HGLRC restore_ctx;
1111 HDC restore_dc;
1112 unsigned int i;
1114 restore_ctx = wglGetCurrentContext();
1115 restore_dc = wglGetCurrentDC();
1117 if (restore_ctx == context->glCtx)
1118 restore_ctx = NULL;
1119 else if (context->valid)
1120 context_set_gl_context(context);
1122 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
1124 if (context->valid)
1125 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
1126 timestamp_query->context = NULL;
1129 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1131 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1132 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1133 occlusion_query->context = NULL;
1136 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
1138 if (context->valid)
1140 if (gl_info->supported[ARB_SYNC])
1142 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
1144 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
1145 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
1147 event_query->context = NULL;
1150 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1152 if (!context->valid) entry->id = 0;
1153 context_destroy_fbo_entry(context, entry);
1156 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1158 if (!context->valid) entry->id = 0;
1159 context_destroy_fbo_entry(context, entry);
1162 if (context->valid)
1164 if (context->dummy_arbfp_prog)
1166 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1169 if (gl_info->supported[ARB_TIMER_QUERY])
1170 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1172 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1173 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1175 if (gl_info->supported[ARB_SYNC])
1177 for (i = 0; i < context->free_event_query_count; ++i)
1179 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
1182 else if (gl_info->supported[APPLE_FENCE])
1184 for (i = 0; i < context->free_event_query_count; ++i)
1186 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1189 else if (gl_info->supported[NV_FENCE])
1191 for (i = 0; i < context->free_event_query_count; ++i)
1193 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1197 checkGLcall("context cleanup");
1200 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1201 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1202 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1204 context_restore_pixel_format(context);
1205 if (restore_ctx)
1207 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1209 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1211 ERR("Failed to disable GL context.\n");
1214 wined3d_release_dc(context->win_handle, context->hdc);
1216 if (!wglDeleteContext(context->glCtx))
1218 DWORD err = GetLastError();
1219 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1223 DWORD context_get_tls_idx(void)
1225 return wined3d_context_tls_idx;
1228 void context_set_tls_idx(DWORD idx)
1230 wined3d_context_tls_idx = idx;
1233 struct wined3d_context *context_get_current(void)
1235 return TlsGetValue(wined3d_context_tls_idx);
1238 BOOL context_set_current(struct wined3d_context *ctx)
1240 struct wined3d_context *old = context_get_current();
1242 if (old == ctx)
1244 TRACE("Already using D3D context %p.\n", ctx);
1245 return TRUE;
1248 if (old)
1250 if (old->destroyed)
1252 TRACE("Switching away from destroyed context %p.\n", old);
1253 context_destroy_gl_resources(old);
1254 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1255 HeapFree(GetProcessHeap(), 0, old);
1257 else
1259 if (wglGetCurrentContext())
1261 TRACE("Flushing context %p before switching to %p.\n", old, ctx);
1262 glFlush();
1264 old->current = 0;
1268 if (ctx)
1270 if (!ctx->valid)
1272 ERR("Trying to make invalid context %p current\n", ctx);
1273 return FALSE;
1276 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1277 if (!context_set_gl_context(ctx))
1278 return FALSE;
1279 ctx->current = 1;
1281 else if(wglGetCurrentContext())
1283 TRACE("Clearing current D3D context.\n");
1284 if (!wglMakeCurrent(NULL, NULL))
1286 DWORD err = GetLastError();
1287 ERR("Failed to clear current GL context, last error %#x.\n", err);
1288 TlsSetValue(wined3d_context_tls_idx, NULL);
1289 return FALSE;
1293 return TlsSetValue(wined3d_context_tls_idx, ctx);
1296 void context_release(struct wined3d_context *context)
1298 TRACE("Releasing context %p, level %u.\n", context, context->level);
1300 if (WARN_ON(d3d))
1302 if (!context->level)
1303 WARN("Context %p is not active.\n", context);
1304 else if (context != context_get_current())
1305 WARN("Context %p is not the current context.\n", context);
1308 if (!--context->level)
1310 if (context_restore_pixel_format(context))
1311 context->needs_set = 1;
1312 if (context->restore_ctx)
1314 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1315 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1316 context->restore_ctx = NULL;
1317 context->restore_dc = NULL;
1322 /* This is used when a context for render target A is active, but a separate context is
1323 * needed to access the WGL framebuffer for render target B. Re-acquire a context for rt
1324 * A to avoid breaking caller code. */
1325 void context_restore(struct wined3d_context *context, struct wined3d_surface *restore)
1327 if (context->current_rt.texture != restore->container
1328 || context->current_rt.sub_resource_idx != surface_get_sub_resource_idx(restore))
1330 context_release(context);
1331 context = context_acquire(restore->container->resource.device, restore);
1334 context_release(context);
1337 static void context_enter(struct wined3d_context *context)
1339 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1341 if (!context->level++)
1343 const struct wined3d_context *current_context = context_get_current();
1344 HGLRC current_gl = wglGetCurrentContext();
1346 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1348 TRACE("Another GL context (%p on device context %p) is already current.\n",
1349 current_gl, wglGetCurrentDC());
1350 context->restore_ctx = current_gl;
1351 context->restore_dc = wglGetCurrentDC();
1352 context->needs_set = 1;
1354 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1355 && context->pixel_format != context->gl_info->gl_ops.wgl.p_wglGetPixelFormat(context->hdc))
1356 context->needs_set = 1;
1360 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1362 DWORD rep = context->state_table[state].representative;
1363 DWORD idx;
1364 BYTE shift;
1366 if (isStateDirty(context, rep)) return;
1368 context->dirtyArray[context->numDirtyEntries++] = rep;
1369 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1370 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1371 context->isStateDirty[idx] |= (1u << shift);
1374 /* This function takes care of wined3d pixel format selection. */
1375 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1376 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1377 BOOL auxBuffers, BOOL findCompatible)
1379 int iPixelFormat=0;
1380 unsigned int current_value;
1381 unsigned int cfg_count = device->adapter->cfg_count;
1382 unsigned int i;
1384 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1385 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1386 auxBuffers, findCompatible);
1388 current_value = 0;
1389 for (i = 0; i < cfg_count; ++i)
1391 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1392 unsigned int value;
1394 /* For now only accept RGBA formats. Perhaps some day we will
1395 * allow floating point formats for pbuffers. */
1396 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1397 continue;
1398 /* In window mode we need a window drawable format and double buffering. */
1399 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1400 continue;
1401 if (cfg->redSize < color_format->red_size)
1402 continue;
1403 if (cfg->greenSize < color_format->green_size)
1404 continue;
1405 if (cfg->blueSize < color_format->blue_size)
1406 continue;
1407 if (cfg->alphaSize < color_format->alpha_size)
1408 continue;
1409 if (cfg->depthSize < ds_format->depth_size)
1410 continue;
1411 if (ds_format->stencil_size && cfg->stencilSize != ds_format->stencil_size)
1412 continue;
1413 /* Check multisampling support. */
1414 if (cfg->numSamples)
1415 continue;
1417 value = 1;
1418 /* We try to locate a format which matches our requirements exactly. In case of
1419 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1420 if (cfg->depthSize == ds_format->depth_size)
1421 value += 1;
1422 if (cfg->stencilSize == ds_format->stencil_size)
1423 value += 2;
1424 if (cfg->alphaSize == color_format->alpha_size)
1425 value += 4;
1426 /* We like to have aux buffers in backbuffer mode */
1427 if (auxBuffers && cfg->auxBuffers)
1428 value += 8;
1429 if (cfg->redSize == color_format->red_size
1430 && cfg->greenSize == color_format->green_size
1431 && cfg->blueSize == color_format->blue_size)
1432 value += 16;
1434 if (value > current_value)
1436 iPixelFormat = cfg->iPixelFormat;
1437 current_value = value;
1441 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1442 if(!iPixelFormat && !findCompatible) {
1443 ERR("Can't find a suitable iPixelFormat\n");
1444 return FALSE;
1445 } else if(!iPixelFormat) {
1446 PIXELFORMATDESCRIPTOR pfd;
1448 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1449 /* PixelFormat selection */
1450 ZeroMemory(&pfd, sizeof(pfd));
1451 pfd.nSize = sizeof(pfd);
1452 pfd.nVersion = 1;
1453 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1454 pfd.iPixelType = PFD_TYPE_RGBA;
1455 pfd.cAlphaBits = color_format->alpha_size;
1456 pfd.cColorBits = color_format->red_size + color_format->green_size
1457 + color_format->blue_size + color_format->alpha_size;
1458 pfd.cDepthBits = ds_format->depth_size;
1459 pfd.cStencilBits = ds_format->stencil_size;
1460 pfd.iLayerType = PFD_MAIN_PLANE;
1462 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1463 if(!iPixelFormat) {
1464 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1465 ERR("Can't find a suitable iPixelFormat\n");
1466 return FALSE;
1470 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1471 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1472 return iPixelFormat;
1475 /* Context activation is done by the caller. */
1476 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1478 const struct wined3d_gl_info *gl_info = context->gl_info;
1479 unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1481 for (i = 0; i < count; ++i)
1483 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1484 checkGLcall("glActiveTexture");
1486 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1487 checkGLcall("glBindTexture");
1489 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1491 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1492 checkGLcall("glBindTexture");
1495 if (gl_info->supported[EXT_TEXTURE3D])
1497 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1498 checkGLcall("glBindTexture");
1501 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1503 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1504 checkGLcall("glBindTexture");
1509 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1511 return gl_info->supported[ARB_DEBUG_OUTPUT]
1512 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1515 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1516 GLenum severity, GLsizei length, const char *message, void *ctx)
1518 switch (type)
1520 case GL_DEBUG_TYPE_ERROR_ARB:
1521 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1522 break;
1524 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1525 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1526 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1527 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1528 break;
1530 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1531 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1532 break;
1534 default:
1535 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1536 break;
1540 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1542 HGLRC ctx;
1543 unsigned int ctx_attrib_idx = 0;
1544 GLint ctx_attribs[7], ctx_flags = 0;
1546 if (context_debug_output_enabled(gl_info))
1547 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1548 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1549 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1550 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1551 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1552 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1553 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1554 if (ctx_flags)
1556 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1557 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1559 ctx_attribs[ctx_attrib_idx] = 0;
1561 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1563 if (ctx_flags & WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
1565 ctx_attribs[ctx_attrib_idx - 1] &= ~WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1566 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1567 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1568 GetLastError());
1571 return ctx;
1574 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1575 struct wined3d_texture *target, const struct wined3d_format *ds_format)
1577 struct wined3d_device *device = swapchain->device;
1578 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1579 const struct wined3d_format *color_format;
1580 struct wined3d_context *ret;
1581 BOOL auxBuffers = FALSE;
1582 HGLRC ctx, share_ctx;
1583 int pixel_format;
1584 unsigned int s;
1585 DWORD state;
1586 HDC hdc = 0;
1587 BOOL hdc_is_private = FALSE;
1589 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1591 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1592 if (!ret)
1593 return NULL;
1595 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1596 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1597 if (!ret->blit_targets)
1598 goto out;
1600 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1601 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1602 if (!ret->draw_buffers)
1603 goto out;
1605 ret->fbo_key = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1606 FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[gl_info->limits.buffers + 1]));
1607 if (!ret->fbo_key)
1608 goto out;
1610 ret->free_timestamp_query_size = 4;
1611 ret->free_timestamp_queries = HeapAlloc(GetProcessHeap(), 0,
1612 ret->free_timestamp_query_size * sizeof(*ret->free_timestamp_queries));
1613 if (!ret->free_timestamp_queries)
1614 goto out;
1615 list_init(&ret->timestamp_queries);
1617 ret->free_occlusion_query_size = 4;
1618 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1619 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1620 if (!ret->free_occlusion_queries)
1621 goto out;
1623 list_init(&ret->occlusion_queries);
1625 ret->free_event_query_size = 4;
1626 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1627 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1628 if (!ret->free_event_queries)
1629 goto out;
1631 list_init(&ret->event_queries);
1632 list_init(&ret->fbo_list);
1633 list_init(&ret->fbo_destroy_list);
1635 if (!device->shader_backend->shader_allocate_context_data(ret))
1637 ERR("Failed to allocate shader backend context data.\n");
1638 goto out;
1640 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1642 ERR("Failed to allocate fragment pipeline context data.\n");
1643 goto out;
1646 /* Initialize the texture unit mapping to a 1:1 mapping */
1647 for (s = 0; s < MAX_COMBINED_SAMPLERS; ++s)
1649 if (s < gl_info->limits.combined_samplers)
1651 ret->tex_unit_map[s] = s;
1652 ret->rev_tex_unit_map[s] = s;
1654 else
1656 ret->tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1657 ret->rev_tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1661 if (!(hdc = GetDCEx(swapchain->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1663 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1665 if ((hdc = swapchain_get_backup_dc(swapchain)))
1666 hdc_is_private = TRUE;
1667 else
1669 ERR("Failed to retrieve a device context.\n");
1670 goto out;
1674 color_format = target->resource.format;
1676 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1677 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1678 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1680 auxBuffers = TRUE;
1682 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1683 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1684 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1685 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1688 /* DirectDraw supports 8bit paletted render targets and these are used by
1689 * old games like StarCraft and C&C. Most modern hardware doesn't support
1690 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1691 * conversion (ab)uses the alpha component for storing the palette index.
1692 * For this reason we require a format with 8bit alpha, so request
1693 * A8R8G8B8. */
1694 if (color_format->id == WINED3DFMT_P8_UINT)
1695 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1697 /* When "always_offscreen" is enabled, we only use the drawable for
1698 * presentation blits, and don't do any rendering to it. That means we
1699 * don't need depth or stencil buffers, and can mostly ignore the render
1700 * target format. This wouldn't necessarily be quite correct for 10bpc
1701 * display modes, but we don't currently support those.
1702 * Using the same format regardless of the color/depth/stencil targets
1703 * makes it much less likely that different wined3d instances will set
1704 * conflicting pixel formats. */
1705 if (wined3d_settings.offscreen_rendering_mode != ORM_BACKBUFFER
1706 && wined3d_settings.always_offscreen)
1708 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1709 ds_format = wined3d_get_format(gl_info, WINED3DFMT_UNKNOWN);
1712 /* Try to find a pixel format which matches our requirements. */
1713 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1715 /* Try to locate a compatible format if we weren't able to find anything. */
1716 if (!pixel_format)
1718 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1719 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1722 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1723 if (!pixel_format)
1725 ERR("Can't find a suitable pixel format.\n");
1726 goto out;
1729 ret->gl_info = gl_info;
1731 context_enter(ret);
1733 if (!context_set_pixel_format(ret, hdc, hdc_is_private, pixel_format))
1735 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1736 context_release(ret);
1737 goto out;
1740 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1741 if (gl_info->p_wglCreateContextAttribsARB)
1743 if (!(ctx = context_create_wgl_attribs(gl_info, hdc, share_ctx)))
1744 goto out;
1746 else
1748 if (!(ctx = wglCreateContext(hdc)))
1750 ERR("Failed to create a WGL context.\n");
1751 context_release(ret);
1752 goto out;
1755 if (share_ctx && !wglShareLists(share_ctx, ctx))
1757 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1758 context_release(ret);
1759 if (!wglDeleteContext(ctx))
1760 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1761 goto out;
1765 if (!device_context_add(device, ret))
1767 ERR("Failed to add the newly created context to the context list\n");
1768 context_release(ret);
1769 if (!wglDeleteContext(ctx))
1770 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1771 goto out;
1774 ret->d3d_info = &device->adapter->d3d_info;
1775 ret->state_table = device->StateTable;
1777 /* Mark all states dirty to force a proper initialization of the states
1778 * on the first use of the context. */
1779 for (state = 0; state <= STATE_HIGHEST; ++state)
1781 if (ret->state_table[state].representative)
1782 context_invalidate_state(ret, state);
1785 ret->swapchain = swapchain;
1786 ret->current_rt.texture = target;
1787 ret->current_rt.sub_resource_idx = 0;
1788 ret->tid = GetCurrentThreadId();
1790 ret->render_offscreen = wined3d_resource_is_offscreen(&target->resource);
1791 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1792 ret->valid = 1;
1794 ret->glCtx = ctx;
1795 ret->win_handle = swapchain->win_handle;
1796 ret->hdc = hdc;
1797 ret->hdc_is_private = hdc_is_private;
1798 ret->hdc_has_format = TRUE;
1799 ret->pixel_format = pixel_format;
1800 ret->needs_set = 1;
1802 /* Set up the context defaults */
1803 if (!context_set_current(ret))
1805 ERR("Cannot activate context to set up defaults.\n");
1806 device_context_remove(device, ret);
1807 context_release(ret);
1808 if (!wglDeleteContext(ctx))
1809 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1810 goto out;
1813 if (context_debug_output_enabled(gl_info))
1815 GL_EXTCALL(glDebugMessageCallback(wined3d_debug_callback, ret));
1816 if (TRACE_ON(d3d_synchronous))
1817 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
1818 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
1819 if (ERR_ON(d3d))
1821 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR,
1822 GL_DONT_CARE, 0, NULL, GL_TRUE));
1824 if (FIXME_ON(d3d))
1826 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
1827 GL_DONT_CARE, 0, NULL, GL_TRUE));
1828 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
1829 GL_DONT_CARE, 0, NULL, GL_TRUE));
1830 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY,
1831 GL_DONT_CARE, 0, NULL, GL_TRUE));
1833 if (WARN_ON(d3d_perf))
1835 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE,
1836 GL_DONT_CARE, 0, NULL, GL_TRUE));
1840 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1842 TRACE("Setting up the screen\n");
1844 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
1846 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1847 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1849 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1850 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1852 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1853 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1855 else
1857 GLuint vao;
1859 GL_EXTCALL(glGenVertexArrays(1, &vao));
1860 GL_EXTCALL(glBindVertexArray(vao));
1861 checkGLcall("creating VAO");
1864 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1865 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1866 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1867 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1869 if (gl_info->supported[ARB_VERTEX_BLEND])
1871 /* Direct3D always uses n-1 weights for n world matrices and uses
1872 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1873 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1874 * enabled as well. */
1875 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1876 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1878 if (gl_info->supported[NV_TEXTURE_SHADER2])
1880 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1881 * the previous texture where to source the offset from is always unit - 1.
1883 for (s = 1; s < gl_info->limits.textures; ++s)
1885 context_active_texture(ret, gl_info, s);
1886 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1887 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1888 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1891 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1893 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1894 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1895 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1896 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1897 * is ever assigned.
1899 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1900 * program and the dummy program is destroyed when the context is destroyed.
1902 static const char dummy_program[] =
1903 "!!ARBfp1.0\n"
1904 "MOV result.color, fragment.color.primary;\n"
1905 "END\n";
1906 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1907 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1908 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1911 if (gl_info->supported[ARB_POINT_SPRITE])
1913 for (s = 0; s < gl_info->limits.textures; ++s)
1915 context_active_texture(ret, gl_info, s);
1916 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1917 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1921 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1923 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1925 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1927 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1929 device->shader_backend->shader_init_context_state(ret);
1930 ret->shader_update_mask = (1u << WINED3D_SHADER_TYPE_PIXEL)
1931 | (1u << WINED3D_SHADER_TYPE_VERTEX)
1932 | (1u << WINED3D_SHADER_TYPE_GEOMETRY)
1933 | (1u << WINED3D_SHADER_TYPE_HULL)
1934 | (1u << WINED3D_SHADER_TYPE_DOMAIN);
1936 /* If this happens to be the first context for the device, dummy textures
1937 * are not created yet. In that case, they will be created (and bound) by
1938 * create_dummy_textures right after this context is initialized. */
1939 if (device->dummy_texture_2d[0])
1940 bind_dummy_textures(device, ret);
1942 TRACE("Created context %p.\n", ret);
1944 return ret;
1946 out:
1947 if (hdc) wined3d_release_dc(swapchain->win_handle, hdc);
1948 device->shader_backend->shader_free_context_data(ret);
1949 device->adapter->fragment_pipe->free_context_data(ret);
1950 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1951 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1952 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
1953 HeapFree(GetProcessHeap(), 0, ret->fbo_key);
1954 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1955 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1956 HeapFree(GetProcessHeap(), 0, ret);
1957 return NULL;
1960 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1962 BOOL destroy;
1964 TRACE("Destroying ctx %p\n", context);
1966 if (context->tid == GetCurrentThreadId() || !context->current)
1968 context_destroy_gl_resources(context);
1969 TlsSetValue(wined3d_context_tls_idx, NULL);
1970 destroy = TRUE;
1972 else
1974 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1975 in wined3d_adapter may go away in the meantime */
1976 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1977 *gl_info = *context->gl_info;
1978 context->gl_info = gl_info;
1979 context->destroyed = 1;
1980 destroy = FALSE;
1983 device->shader_backend->shader_free_context_data(context);
1984 device->adapter->fragment_pipe->free_context_data(context);
1985 HeapFree(GetProcessHeap(), 0, context->fbo_key);
1986 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1987 HeapFree(GetProcessHeap(), 0, context->blit_targets);
1988 device_context_remove(device, context);
1989 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1992 /* Context activation is done by the caller. */
1993 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
1995 const GLdouble projection[] =
1997 2.0 / width, 0.0, 0.0, 0.0,
1998 0.0, 2.0 / height, 0.0, 0.0,
1999 0.0, 0.0, 2.0, 0.0,
2000 -1.0, -1.0, -1.0, 1.0,
2003 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
2004 checkGLcall("glMatrixMode(GL_PROJECTION)");
2005 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
2006 checkGLcall("glLoadMatrixd");
2007 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
2008 checkGLcall("glViewport");
2011 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
2013 const struct wined3d_texture *rt = context->current_rt.texture;
2014 unsigned int level;
2016 if (rt->swapchain && rt->swapchain->front_buffer == rt)
2018 RECT window_size;
2020 GetClientRect(context->win_handle, &window_size);
2021 size->cx = window_size.right - window_size.left;
2022 size->cy = window_size.bottom - window_size.top;
2024 return;
2027 level = context->current_rt.sub_resource_idx % rt->level_count;
2028 size->cx = wined3d_texture_get_level_width(rt, level);
2029 size->cy = wined3d_texture_get_level_height(rt, level);
2032 /*****************************************************************************
2033 * SetupForBlit
2035 * Sets up a context for DirectDraw blitting.
2036 * All texture units are disabled, texture unit 0 is set as current unit
2037 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
2038 * color writing enabled for all channels
2039 * register combiners disabled, shaders disabled
2040 * world matrix is set to identity, texture matrix 0 too
2041 * projection matrix is setup for drawing screen coordinates
2043 * Params:
2044 * This: Device to activate the context for
2045 * context: Context to setup
2047 *****************************************************************************/
2048 /* Context activation is done by the caller. */
2049 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
2051 int i;
2052 const struct wined3d_gl_info *gl_info = context->gl_info;
2053 DWORD sampler;
2054 SIZE rt_size;
2056 TRACE("Setting up context %p for blitting\n", context);
2058 context_get_rt_size(context, &rt_size);
2060 if (context->last_was_blit)
2062 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
2064 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2065 context->blit_w = rt_size.cx;
2066 context->blit_h = rt_size.cy;
2067 /* No need to dirtify here, the states are still dirtified because
2068 * they weren't applied since the last SetupForBlit() call. */
2070 TRACE("Context is already set up for blitting, nothing to do\n");
2071 return;
2073 context->last_was_blit = TRUE;
2075 /* Disable all textures. The caller can then bind a texture it wants to blit
2076 * from
2078 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
2079 * function texture unit. No need to care for higher samplers
2081 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
2083 sampler = context->rev_tex_unit_map[i];
2084 context_active_texture(context, gl_info, i);
2086 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2088 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2089 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2091 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2092 checkGLcall("glDisable GL_TEXTURE_3D");
2093 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2095 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2096 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2098 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2099 checkGLcall("glDisable GL_TEXTURE_2D");
2101 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2102 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
2104 if (sampler != WINED3D_UNMAPPED_STAGE)
2106 if (sampler < MAX_TEXTURES)
2107 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2108 context_invalidate_state(context, STATE_SAMPLER(sampler));
2111 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
2112 GL_EXTCALL(glBindSampler(0, 0));
2113 context_active_texture(context, gl_info, 0);
2115 sampler = context->rev_tex_unit_map[0];
2117 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2119 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2120 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2122 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2123 checkGLcall("glDisable GL_TEXTURE_3D");
2124 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2126 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2127 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2129 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2130 checkGLcall("glDisable GL_TEXTURE_2D");
2132 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2134 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
2135 checkGLcall("glMatrixMode(GL_TEXTURE)");
2136 gl_info->gl_ops.gl.p_glLoadIdentity();
2137 checkGLcall("glLoadIdentity()");
2139 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2141 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
2142 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
2143 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
2146 if (sampler != WINED3D_UNMAPPED_STAGE)
2148 if (sampler < MAX_TEXTURES)
2150 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
2151 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2153 context_invalidate_state(context, STATE_SAMPLER(sampler));
2156 /* Other misc states */
2157 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2158 checkGLcall("glDisable(GL_ALPHA_TEST)");
2159 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2160 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2161 checkGLcall("glDisable GL_LIGHTING");
2162 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2163 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2164 checkGLcall("glDisable GL_DEPTH_TEST");
2165 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2166 glDisableWINE(GL_FOG);
2167 checkGLcall("glDisable GL_FOG");
2168 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
2169 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2170 checkGLcall("glDisable GL_BLEND");
2171 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2172 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2173 checkGLcall("glDisable GL_CULL_FACE");
2174 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2175 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2176 checkGLcall("glDisable GL_STENCIL_TEST");
2177 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2178 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2179 checkGLcall("glDisable GL_SCISSOR_TEST");
2180 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2181 if (gl_info->supported[ARB_POINT_SPRITE])
2183 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2184 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2185 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2187 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2188 checkGLcall("glColorMask");
2189 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2190 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2191 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2192 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2193 if (gl_info->supported[EXT_SECONDARY_COLOR])
2195 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2196 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2197 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2200 /* Setup transforms */
2201 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2202 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2203 gl_info->gl_ops.gl.p_glLoadIdentity();
2204 checkGLcall("glLoadIdentity()");
2205 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2207 context->last_was_rhw = TRUE;
2208 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2210 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2211 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2212 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2213 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2214 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2215 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2216 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2218 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2220 /* Disable shaders */
2221 device->shader_backend->shader_disable(device->shader_priv, context);
2223 context->blit_w = rt_size.cx;
2224 context->blit_h = rt_size.cy;
2225 context_invalidate_state(context, STATE_VIEWPORT);
2226 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2229 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2231 return rt_mask & (1u << 31);
2234 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2236 return rt_mask & ~(1u << 31);
2239 /* Context activation is done by the caller. */
2240 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2242 const struct wined3d_gl_info *gl_info = context->gl_info;
2244 if (!rt_mask)
2246 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2247 checkGLcall("glDrawBuffer()");
2249 else if (is_rt_mask_onscreen(rt_mask))
2251 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2252 checkGLcall("glDrawBuffer()");
2254 else
2256 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2258 unsigned int i = 0;
2260 while (rt_mask)
2262 if (rt_mask & 1)
2263 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2264 else
2265 context->draw_buffers[i] = GL_NONE;
2267 rt_mask >>= 1;
2268 ++i;
2271 if (gl_info->supported[ARB_DRAW_BUFFERS])
2273 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2274 checkGLcall("glDrawBuffers()");
2276 else
2278 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2279 checkGLcall("glDrawBuffer()");
2282 else
2284 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2289 /* Context activation is done by the caller. */
2290 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2292 const struct wined3d_gl_info *gl_info = context->gl_info;
2293 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2294 DWORD new_mask = context_generate_rt_mask(buffer);
2296 if (new_mask == *current_mask)
2297 return;
2299 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2300 checkGLcall("glDrawBuffer()");
2302 *current_mask = new_mask;
2305 /* Context activation is done by the caller. */
2306 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2308 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2309 checkGLcall("glActiveTexture");
2310 context->active_texture = unit;
2313 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2315 const struct wined3d_gl_info *gl_info = context->gl_info;
2316 DWORD unit = context->active_texture;
2317 DWORD old_texture_type = context->texture_type[unit];
2319 if (name)
2321 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2322 checkGLcall("glBindTexture");
2324 else
2326 target = GL_NONE;
2329 if (old_texture_type != target)
2331 const struct wined3d_device *device = context->swapchain->device;
2333 switch (old_texture_type)
2335 case GL_NONE:
2336 /* nothing to do */
2337 break;
2338 case GL_TEXTURE_2D:
2339 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
2340 checkGLcall("glBindTexture");
2341 break;
2342 case GL_TEXTURE_RECTANGLE_ARB:
2343 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
2344 checkGLcall("glBindTexture");
2345 break;
2346 case GL_TEXTURE_CUBE_MAP:
2347 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
2348 checkGLcall("glBindTexture");
2349 break;
2350 case GL_TEXTURE_3D:
2351 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
2352 checkGLcall("glBindTexture");
2353 break;
2354 default:
2355 ERR("Unexpected texture target %#x\n", old_texture_type);
2358 context->texture_type[unit] = target;
2362 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2364 if (context->render_offscreen == offscreen) return;
2366 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2367 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2368 context_invalidate_state(context, STATE_VIEWPORT);
2369 context_invalidate_state(context, STATE_SCISSORRECT);
2370 context_invalidate_state(context, STATE_FRONTFACE);
2371 context->render_offscreen = offscreen;
2374 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2375 const struct wined3d_format *required)
2377 if (existing == required)
2378 return TRUE;
2379 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2380 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2381 return FALSE;
2382 if (existing->depth_size < required->depth_size)
2383 return FALSE;
2384 /* If stencil bits are used the exact amount is required - otherwise
2385 * wrapping won't work correctly. */
2386 if (required->stencil_size && required->stencil_size != existing->stencil_size)
2387 return FALSE;
2388 return TRUE;
2391 /* Context activation is done by the caller. */
2392 static void context_validate_onscreen_formats(struct wined3d_context *context,
2393 const struct wined3d_rendertarget_view *depth_stencil)
2395 /* Onscreen surfaces are always in a swapchain */
2396 struct wined3d_swapchain *swapchain = context->current_rt.texture->swapchain;
2397 struct wined3d_surface *surface;
2399 if (context->render_offscreen || !depth_stencil) return;
2400 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2402 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2403 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2404 * format. */
2405 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2407 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2408 surface = context->current_rt.texture->sub_resources[context->current_rt.sub_resource_idx].u.surface;
2409 surface_load_location(surface, context, WINED3D_LOCATION_TEXTURE_RGB);
2410 swapchain->render_to_fbo = TRUE;
2411 swapchain_update_draw_bindings(swapchain);
2412 context_set_render_offscreen(context, TRUE);
2415 GLenum context_get_offscreen_gl_buffer(const struct wined3d_context *context)
2417 switch (wined3d_settings.offscreen_rendering_mode)
2419 case ORM_FBO:
2420 return GL_COLOR_ATTACHMENT0;
2422 case ORM_BACKBUFFER:
2423 return context->aux_buffers > 0 ? GL_AUX0 : GL_BACK;
2425 default:
2426 FIXME("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
2427 return GL_BACK;
2431 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_context *context, struct wined3d_texture *rt)
2433 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2434 return 0;
2435 else if (rt->swapchain)
2436 return context_generate_rt_mask_from_resource(&rt->resource);
2437 else
2438 return context_generate_rt_mask(context_get_offscreen_gl_buffer(context));
2441 /* Context activation is done by the caller. */
2442 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2444 struct wined3d_texture *rt = context->current_rt.texture;
2445 struct wined3d_surface *surface;
2446 DWORD rt_mask, *cur_mask;
2448 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2450 context_validate_onscreen_formats(context, NULL);
2452 if (context->render_offscreen)
2454 wined3d_texture_load(rt, context, FALSE);
2456 surface = rt->sub_resources[context->current_rt.sub_resource_idx].u.surface;
2457 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, surface, NULL, rt->resource.draw_binding);
2458 if (rt->resource.format->id != WINED3DFMT_NULL)
2459 rt_mask = 1;
2460 else
2461 rt_mask = 0;
2463 else
2465 context->current_fbo = NULL;
2466 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2467 rt_mask = context_generate_rt_mask_from_resource(&rt->resource);
2470 else
2472 rt_mask = context_generate_rt_mask_no_fbo(context, rt);
2475 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2477 if (rt_mask != *cur_mask)
2479 context_apply_draw_buffers(context, rt_mask);
2480 *cur_mask = rt_mask;
2483 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2485 context_check_fbo_status(context, GL_FRAMEBUFFER);
2488 SetupForBlit(device, context);
2489 context_invalidate_state(context, STATE_FRAMEBUFFER);
2492 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2493 const struct wined3d_rendertarget_view *ds)
2495 unsigned int i;
2497 if (ds) return TRUE;
2499 for (i = 0; i < rt_count; ++i)
2501 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2502 return TRUE;
2505 WARN("Invalid render target config, need at least one attachment.\n");
2506 return FALSE;
2509 /* Context activation is done by the caller. */
2510 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_state *state,
2511 UINT rt_count, const struct wined3d_fb_state *fb)
2513 struct wined3d_rendertarget_view **rts = fb->render_targets;
2514 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2515 const struct wined3d_gl_info *gl_info = context->gl_info;
2516 DWORD rt_mask = 0, *cur_mask;
2517 UINT i;
2519 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != state->fb
2520 || rt_count != gl_info->limits.buffers)
2522 if (!context_validate_rt_config(rt_count, rts, dsv))
2523 return FALSE;
2525 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2527 context_validate_onscreen_formats(context, dsv);
2529 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2531 for (i = 0; i < rt_count; ++i)
2533 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(rts[i]);
2534 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2535 rt_mask |= (1u << i);
2537 while (i < gl_info->limits.buffers)
2539 context->blit_targets[i] = NULL;
2540 ++i;
2542 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2543 wined3d_rendertarget_view_get_surface(dsv),
2544 rt_count ? rts[0]->resource->draw_binding : 0,
2545 dsv ? dsv->resource->draw_binding : 0);
2547 else
2549 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2550 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2551 rt_mask = context_generate_rt_mask_from_resource(rts[0]->resource);
2554 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2555 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2556 * state management allows this */
2557 context_invalidate_state(context, STATE_FRAMEBUFFER);
2559 else
2561 rt_mask = context_generate_rt_mask_no_fbo(context,
2562 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
2565 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2566 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
2568 for (i = 0; i < rt_count; ++i)
2570 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2571 rt_mask |= (1u << i);
2574 else
2576 rt_mask = context_generate_rt_mask_no_fbo(context,
2577 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
2580 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2582 if (rt_mask != *cur_mask)
2584 context_apply_draw_buffers(context, rt_mask);
2585 *cur_mask = rt_mask;
2586 context_invalidate_state(context, STATE_FRAMEBUFFER);
2589 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2591 context_check_fbo_status(context, GL_FRAMEBUFFER);
2594 if (context->last_was_blit)
2595 context->last_was_blit = FALSE;
2597 /* Blending and clearing should be orthogonal, but tests on the nvidia
2598 * driver show that disabling blending when clearing improves the clearing
2599 * performance incredibly. */
2600 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2601 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2602 if (rt_count && gl_info->supported[ARB_FRAMEBUFFER_SRGB])
2604 if (needs_srgb_write(context, state, fb))
2605 gl_info->gl_ops.gl.p_glEnable(GL_FRAMEBUFFER_SRGB);
2606 else
2607 gl_info->gl_ops.gl.p_glDisable(GL_FRAMEBUFFER_SRGB);
2608 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2610 checkGLcall("setting up state for clear");
2612 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2613 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2614 context_invalidate_state(context, STATE_SCISSORRECT);
2616 return TRUE;
2619 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_state *state)
2621 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
2622 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2623 DWORD rt_mask, rt_mask_bits;
2624 unsigned int i;
2626 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2627 return context_generate_rt_mask_no_fbo(context, wined3d_rendertarget_view_get_surface(rts[0])->container);
2628 else if (!context->render_offscreen)
2629 return context_generate_rt_mask_from_resource(rts[0]->resource);
2631 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2632 rt_mask &= context->d3d_info->valid_rt_mask;
2633 rt_mask_bits = rt_mask;
2634 i = 0;
2635 while (rt_mask_bits)
2637 rt_mask_bits &= ~(1u << i);
2638 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
2639 rt_mask &= ~(1u << i);
2641 i++;
2644 return rt_mask;
2647 /* Context activation is done by the caller. */
2648 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2650 DWORD rt_mask = find_draw_buffers_mask(context, state);
2651 const struct wined3d_fb_state *fb = state->fb;
2652 DWORD *cur_mask;
2654 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2656 if (!context->render_offscreen)
2658 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2659 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2661 else
2663 unsigned int i;
2665 for (i = 0; i < context->gl_info->limits.buffers; ++i)
2667 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(fb->render_targets[i]);
2669 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2670 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
2671 fb->render_targets[0] ? fb->render_targets[0]->resource->draw_binding : 0,
2672 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
2676 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2677 if (rt_mask != *cur_mask)
2679 context_apply_draw_buffers(context, rt_mask);
2680 *cur_mask = rt_mask;
2684 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
2686 DWORD i = context->rev_tex_unit_map[unit];
2687 DWORD j = context->tex_unit_map[stage];
2689 TRACE("Mapping stage %u to unit %u.\n", stage, unit);
2690 context->tex_unit_map[stage] = unit;
2691 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2692 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2694 context->rev_tex_unit_map[unit] = stage;
2695 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2696 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2699 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
2701 DWORD i;
2703 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2704 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
2707 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
2708 const struct wined3d_state *state)
2710 UINT i, start, end;
2712 context->fixed_function_usage_map = 0;
2713 for (i = 0; i < MAX_TEXTURES; ++i)
2715 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2716 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2717 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2718 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2719 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2720 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2721 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2722 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2724 /* Not used, and disable higher stages. */
2725 if (color_op == WINED3D_TOP_DISABLE)
2726 break;
2728 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2729 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2730 || ((color_arg3 == WINED3DTA_TEXTURE)
2731 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2732 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2733 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2734 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2735 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2736 context->fixed_function_usage_map |= (1u << i);
2738 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2739 && i < MAX_TEXTURES - 1)
2740 context->fixed_function_usage_map |= (1u << (i + 1));
2743 if (i < context->lowest_disabled_stage)
2745 start = i;
2746 end = context->lowest_disabled_stage;
2748 else
2750 start = context->lowest_disabled_stage;
2751 end = i;
2754 context->lowest_disabled_stage = i;
2755 for (i = start + 1; i < end; ++i)
2757 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
2761 static void context_map_fixed_function_samplers(struct wined3d_context *context,
2762 const struct wined3d_state *state)
2764 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2765 const struct wined3d_gl_info *gl_info = context->gl_info;
2766 unsigned int i, tex;
2767 WORD ffu_map;
2769 context_update_fixed_function_usage_map(context, state);
2771 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2772 return;
2774 ffu_map = context->fixed_function_usage_map;
2776 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
2777 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
2779 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2781 if (!(ffu_map & 1))
2782 continue;
2784 if (context->tex_unit_map[i] != i)
2786 context_map_stage(context, i, i);
2787 context_invalidate_state(context, STATE_SAMPLER(i));
2788 context_invalidate_texture_stage(context, i);
2791 return;
2794 /* Now work out the mapping */
2795 tex = 0;
2796 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2798 if (!(ffu_map & 1))
2799 continue;
2801 if (context->tex_unit_map[i] != tex)
2803 context_map_stage(context, i, tex);
2804 context_invalidate_state(context, STATE_SAMPLER(i));
2805 context_invalidate_texture_stage(context, i);
2808 ++tex;
2812 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
2814 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2815 const struct wined3d_gl_info *gl_info = context->gl_info;
2816 const struct wined3d_shader_resource_info *resource_info =
2817 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2818 unsigned int i;
2820 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2821 return;
2823 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2825 if (resource_info[i].type && context->tex_unit_map[i] != i)
2827 context_map_stage(context, i, i);
2828 context_invalidate_state(context, STATE_SAMPLER(i));
2829 if (i < d3d_info->limits.ffp_blend_stages)
2830 context_invalidate_texture_stage(context, i);
2835 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
2836 const struct wined3d_shader_resource_info *ps_resource_info, DWORD unit)
2838 DWORD current_mapping = context->rev_tex_unit_map[unit];
2840 /* Not currently used */
2841 if (current_mapping == WINED3D_UNMAPPED_STAGE)
2842 return TRUE;
2844 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
2846 /* Used by a fragment sampler */
2848 if (!ps_resource_info)
2850 /* No pixel shader, check fixed function */
2851 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1u << current_mapping));
2854 /* Pixel shader, check the shader's sampler map */
2855 return !ps_resource_info[current_mapping].type;
2858 return TRUE;
2861 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
2863 const struct wined3d_shader_resource_info *vs_resource_info =
2864 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
2865 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
2866 const struct wined3d_gl_info *gl_info = context->gl_info;
2867 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2868 int i;
2870 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2871 return;
2873 /* Note that we only care if a resource is used or not, not the
2874 * resource's specific type. Otherwise we'd need to call
2875 * shader_update_samplers() here for 1.x pixelshaders. */
2876 if (ps)
2877 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2879 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2881 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2882 if (vs_resource_info[i].type)
2884 while (start >= 0)
2886 if (context_unit_free_for_vs(context, ps_resource_info, start))
2888 if (context->tex_unit_map[vsampler_idx] != start)
2890 context_map_stage(context, vsampler_idx, start);
2891 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
2894 --start;
2895 break;
2898 --start;
2900 if (context->tex_unit_map[vsampler_idx] == WINED3D_UNMAPPED_STAGE)
2901 WARN("Couldn't find a free texture unit for vertex sampler %u.\n", i);
2906 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
2908 BOOL vs = use_vs(state);
2909 BOOL ps = use_ps(state);
2911 /* Try to go for a 1:1 mapping of the samplers when possible. Pixel shaders
2912 * need a 1:1 map at the moment.
2913 * When the mapping of a stage is changed, sampler and ALL texture stage
2914 * states have to be reset. */
2916 if (ps)
2917 context_map_psamplers(context, state);
2918 else
2919 context_map_fixed_function_samplers(context, state);
2921 if (vs)
2922 context_map_vsamplers(context, ps, state);
2925 /* Context activation is done by the caller. */
2926 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2928 DWORD rt_mask, *cur_mask;
2930 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2932 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2933 rt_mask = find_draw_buffers_mask(context, state);
2934 if (rt_mask != *cur_mask)
2936 context_apply_draw_buffers(context, rt_mask);
2937 *cur_mask = rt_mask;
2941 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
2943 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
2944 *regnum = WINED3D_FFP_POSITION;
2945 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
2946 *regnum = WINED3D_FFP_BLENDWEIGHT;
2947 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
2948 *regnum = WINED3D_FFP_BLENDINDICES;
2949 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
2950 *regnum = WINED3D_FFP_NORMAL;
2951 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
2952 *regnum = WINED3D_FFP_PSIZE;
2953 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
2954 *regnum = WINED3D_FFP_DIFFUSE;
2955 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
2956 *regnum = WINED3D_FFP_SPECULAR;
2957 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
2958 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
2959 else
2961 FIXME("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
2962 *regnum = ~0U;
2963 return FALSE;
2966 return TRUE;
2969 /* Context activation is done by the caller. */
2970 void context_stream_info_from_declaration(struct wined3d_context *context,
2971 const struct wined3d_state *state, struct wined3d_stream_info *stream_info)
2973 /* We need to deal with frequency data! */
2974 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
2975 BOOL use_vshader = use_vs(state);
2976 BOOL generic_attributes = context->d3d_info->ffp_generic_attributes;
2977 unsigned int i;
2979 stream_info->use_map = 0;
2980 stream_info->swizzle_map = 0;
2981 stream_info->position_transformed = declaration->position_transformed;
2983 /* Translate the declaration into strided data. */
2984 for (i = 0; i < declaration->element_count; ++i)
2986 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
2987 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
2988 BOOL stride_used;
2989 unsigned int idx;
2991 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
2992 element, i + 1, declaration->element_count);
2994 if (!stream->buffer)
2995 continue;
2997 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
2999 if (use_vshader)
3001 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
3003 stride_used = FALSE;
3005 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
3007 /* TODO: Assuming vertexdeclarations are usually used with the
3008 * same or a similar shader, it might be worth it to store the
3009 * last used output slot and try that one first. */
3010 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
3011 element->usage, element->usage_idx, &idx);
3013 else
3015 idx = element->output_slot;
3016 stride_used = TRUE;
3019 else
3021 if (!generic_attributes && !element->ffp_valid)
3023 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
3024 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
3025 stride_used = FALSE;
3027 else
3029 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
3033 if (stride_used)
3035 TRACE("Load %s array %u [usage %s, usage_idx %u, "
3036 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
3037 use_vshader ? "shader": "fixed function", idx,
3038 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
3039 element->offset, stream->stride, debug_d3dformat(element->format->id),
3040 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
3042 stream_info->elements[idx].format = element->format;
3043 stream_info->elements[idx].data.buffer_object = 0;
3044 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
3045 stream_info->elements[idx].stride = stream->stride;
3046 stream_info->elements[idx].stream_idx = element->input_slot;
3047 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
3049 stream_info->elements[idx].divisor = 1;
3051 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
3053 stream_info->elements[idx].divisor = element->instance_data_step_rate;
3054 if (!element->instance_data_step_rate)
3055 FIXME("Instance step rate 0 not implemented.\n");
3057 else
3059 stream_info->elements[idx].divisor = 0;
3062 if (!context->gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3063 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
3065 stream_info->swizzle_map |= 1u << idx;
3067 stream_info->use_map |= 1u << idx;
3072 /* Context activation is done by the caller. */
3073 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
3075 const struct wined3d_gl_info *gl_info = context->gl_info;
3076 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3077 struct wined3d_stream_info *stream_info = &context->stream_info;
3078 DWORD prev_all_vbo = stream_info->all_vbo;
3079 unsigned int i;
3080 WORD map;
3082 context_stream_info_from_declaration(context, state, stream_info);
3084 stream_info->all_vbo = 1;
3085 context->num_buffer_queries = 0;
3086 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
3088 struct wined3d_stream_info_element *element;
3089 struct wined3d_bo_address data;
3090 struct wined3d_buffer *buffer;
3092 if (!(map & 1))
3093 continue;
3095 element = &stream_info->elements[i];
3096 buffer = state->streams[element->stream_idx].buffer;
3098 /* We can't use VBOs if the base vertex index is negative. OpenGL
3099 * doesn't accept negative offsets (or rather offsets bigger than the
3100 * VBO, because the pointer is unsigned), so use system memory
3101 * sources. In most sane cases the pointer - offset will still be > 0,
3102 * otherwise it will wrap around to some big value. Hope that with the
3103 * indices the driver wraps it back internally. If not,
3104 * draw_primitive_immediate_mode() is needed, including a vertex buffer
3105 * path. */
3106 if (state->load_base_vertex_index < 0)
3108 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
3109 state->load_base_vertex_index);
3110 element->data.buffer_object = 0;
3111 element->data.addr += (ULONG_PTR)buffer_get_sysmem(buffer, context);
3112 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
3113 FIXME("System memory vertex data load offset is negative!\n");
3115 else
3117 buffer_internal_preload(buffer, context, state);
3118 buffer_get_memory(buffer, context, &data);
3119 element->data.buffer_object = data.buffer_object;
3120 element->data.addr += (ULONG_PTR)data.addr;
3123 if (!element->data.buffer_object)
3124 stream_info->all_vbo = 0;
3126 if (buffer->query)
3127 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
3129 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
3132 if (use_vs(state))
3134 if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
3136 TRACE("Using immediate mode draw with vertex shaders for FLOAT16 conversion.\n");
3137 context->use_immediate_mode_draw = TRUE;
3139 else
3141 context->use_immediate_mode_draw = FALSE;
3144 else
3146 WORD slow_mask = -!d3d_info->ffp_generic_attributes & (1u << WINED3D_FFP_PSIZE);
3147 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3148 & ((1u << WINED3D_FFP_DIFFUSE) | (1u << WINED3D_FFP_SPECULAR));
3150 if (((stream_info->position_transformed && !d3d_info->xyzrhw)
3151 || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
3152 context->use_immediate_mode_draw = TRUE;
3153 else
3154 context->use_immediate_mode_draw = FALSE;
3157 if (prev_all_vbo != stream_info->all_vbo)
3158 context_invalidate_state(context, STATE_INDEXBUFFER);
3161 /* Context activation is done by the caller. */
3162 static void context_preload_texture(struct wined3d_context *context,
3163 const struct wined3d_state *state, unsigned int idx)
3165 struct wined3d_texture *texture;
3167 if (!(texture = state->textures[idx]))
3168 return;
3170 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3173 /* Context activation is done by the caller. */
3174 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3176 unsigned int i;
3178 if (use_vs(state))
3180 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3182 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3183 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3187 if (use_ps(state))
3189 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3191 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3192 context_preload_texture(context, state, i);
3195 else
3197 WORD ffu_map = context->fixed_function_usage_map;
3199 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3201 if (ffu_map & 1)
3202 context_preload_texture(context, state, i);
3207 static void context_load_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3209 struct wined3d_shader_sampler_map_entry *entry;
3210 struct wined3d_shader_resource_view *view;
3211 struct wined3d_shader *shader;
3212 unsigned int i, j;
3214 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3216 if (!(shader = state->shader[i]))
3217 continue;
3219 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3221 if (state->cb[i][j])
3222 buffer_internal_preload(state->cb[i][j], context, state);
3225 for (j = 0; j < shader->reg_maps.sampler_map.count; ++j)
3227 entry = &shader->reg_maps.sampler_map.entries[j];
3229 if (!(view = state->shader_resource_view[i][entry->resource_idx]))
3231 WARN("No resource view bound at index %u, %u.\n", i, entry->resource_idx);
3232 continue;
3235 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3236 buffer_internal_preload(buffer_from_resource(view->resource), context, state);
3237 else
3238 wined3d_texture_load(wined3d_texture_from_resource(view->resource), context, FALSE);
3243 static void context_bind_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3245 const struct wined3d_device *device = context->swapchain->device;
3246 const struct wined3d_gl_info *gl_info = context->gl_info;
3247 struct wined3d_shader_sampler_map_entry *entry;
3248 struct wined3d_shader_resource_view *view;
3249 struct wined3d_sampler *sampler;
3250 struct wined3d_texture *texture;
3251 struct wined3d_shader *shader;
3252 unsigned int i, j, count;
3253 GLuint sampler_name;
3255 static const struct
3257 enum wined3d_shader_type type;
3258 unsigned int base_idx;
3259 unsigned int count;
3261 shader_types[] =
3263 {WINED3D_SHADER_TYPE_PIXEL, 0, MAX_FRAGMENT_SAMPLERS},
3264 {WINED3D_SHADER_TYPE_VERTEX, MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS},
3267 for (i = 0; i < ARRAY_SIZE(shader_types); ++i)
3269 if (!(shader = state->shader[shader_types[i].type]))
3270 continue;
3272 count = shader->reg_maps.sampler_map.count;
3273 if (count > shader_types[i].count)
3275 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3276 shader, count, shader_types[i].count);
3277 count = shader_types[i].count;
3280 for (j = 0; j < count; ++j)
3282 entry = &shader->reg_maps.sampler_map.entries[j];
3284 if (!(view = state->shader_resource_view[shader_types[i].type][entry->resource_idx]))
3286 WARN("No resource view bound at index %u, %u.\n", shader_types[i].type, entry->resource_idx);
3287 continue;
3290 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3292 FIXME("Buffer shader resources not supported.\n");
3293 continue;
3296 if (entry->sampler_idx == WINED3D_SAMPLER_DEFAULT)
3298 sampler_name = device->default_sampler;
3300 else if ((sampler = state->sampler[shader_types[i].type][entry->sampler_idx]))
3302 sampler_name = sampler->name;
3304 else
3306 WARN("No sampler object bound at index %u, %u.\n", shader_types[i].type, entry->sampler_idx);
3307 continue;
3310 texture = wined3d_texture_from_resource(view->resource);
3311 context_active_texture(context, gl_info, shader_types[i].base_idx + entry->bind_idx);
3312 wined3d_texture_bind(texture, context, FALSE);
3314 GL_EXTCALL(glBindSampler(shader_types[i].base_idx + entry->bind_idx, sampler_name));
3315 checkGLcall("glBindSampler");
3320 /* Context activation is done by the caller. */
3321 BOOL context_apply_draw_state(struct wined3d_context *context, struct wined3d_device *device)
3323 const struct wined3d_state *state = &device->state;
3324 const struct StateEntry *state_table = context->state_table;
3325 const struct wined3d_fb_state *fb = state->fb;
3326 unsigned int i;
3327 WORD map;
3329 if (!context_validate_rt_config(context->gl_info->limits.buffers,
3330 fb->render_targets, fb->depth_stencil))
3331 return FALSE;
3333 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3335 context_validate_onscreen_formats(context, fb->depth_stencil);
3338 /* Preload resources before FBO setup. Texture preload in particular may
3339 * result in changes to the current FBO, due to using e.g. FBO blits for
3340 * updating a resource location. */
3341 context_update_tex_unit_map(context, state);
3342 context_preload_textures(context, state);
3343 context_load_shader_resources(context, state);
3344 /* TODO: Right now the dependency on the vertex shader is necessary
3345 * since context_stream_info_from_declaration depends on the reg_maps of
3346 * the current VS but maybe it's possible to relax the coupling in some
3347 * situations at least. */
3348 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3349 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3351 context_update_stream_info(context, state);
3353 else
3355 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3357 if (map & 1)
3358 buffer_mark_used(state->streams[context->stream_info.elements[i].stream_idx].buffer);
3361 if (state->index_buffer)
3363 if (context->stream_info.all_vbo)
3364 buffer_internal_preload(state->index_buffer, context, state);
3365 else
3366 buffer_get_sysmem(state->index_buffer, context);
3369 for (i = 0; i < context->numDirtyEntries; ++i)
3371 DWORD rep = context->dirtyArray[i];
3372 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3373 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3374 context->isStateDirty[idx] &= ~(1u << shift);
3375 state_table[rep].apply(context, state, rep);
3378 if (context->shader_update_mask)
3380 device->shader_backend->shader_select(device->shader_priv, context, state);
3381 context->shader_update_mask = 0;
3384 if (context->constant_update_mask)
3386 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3387 context->constant_update_mask = 0;
3390 if (context->update_shader_resource_bindings)
3392 context_bind_shader_resources(context, state);
3393 context->update_shader_resource_bindings = 0;
3396 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3398 context_check_fbo_status(context, GL_FRAMEBUFFER);
3401 context->numDirtyEntries = 0; /* This makes the whole list clean */
3402 context->last_was_blit = FALSE;
3404 return TRUE;
3407 static void context_setup_target(struct wined3d_context *context,
3408 struct wined3d_texture *texture, unsigned int sub_resource_idx)
3410 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
3412 render_offscreen = wined3d_resource_is_offscreen(&texture->resource);
3413 if (context->current_rt.texture == texture
3414 && context->current_rt.sub_resource_idx == sub_resource_idx
3415 && render_offscreen == old_render_offscreen)
3416 return;
3418 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
3419 * the alpha blend state changes with different render target formats. */
3420 if (!context->current_rt.texture)
3422 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3424 else
3426 const struct wined3d_format *old = context->current_rt.texture->resource.format;
3427 const struct wined3d_format *new = texture->resource.format;
3429 if (old->id != new->id)
3431 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
3432 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
3433 || !(texture->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
3434 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3436 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
3437 if ((context->current_rt.texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
3438 != (texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
3439 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3442 /* When switching away from an offscreen render target, and we're not
3443 * using FBOs, we have to read the drawable into the texture. This is
3444 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
3445 * There are some things that need care though. PreLoad needs a GL context,
3446 * and FindContext is called before the context is activated. It also
3447 * has to be called with the old rendertarget active, otherwise a
3448 * wrong drawable is read. */
3449 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
3450 && old_render_offscreen && (context->current_rt.texture != texture
3451 || context->current_rt.sub_resource_idx != sub_resource_idx))
3453 unsigned int prev_sub_resource_idx = context->current_rt.sub_resource_idx;
3454 struct wined3d_texture *prev_texture = context->current_rt.texture;
3456 /* Read the back buffer of the old drawable into the destination texture. */
3457 if (prev_texture->texture_srgb.name)
3458 wined3d_texture_load(prev_texture, context, TRUE);
3459 wined3d_texture_load(prev_texture, context, FALSE);
3460 wined3d_texture_invalidate_location(prev_texture, prev_sub_resource_idx, WINED3D_LOCATION_DRAWABLE);
3464 context->current_rt.texture = texture;
3465 context->current_rt.sub_resource_idx = sub_resource_idx;
3466 context_set_render_offscreen(context, render_offscreen);
3469 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
3471 struct wined3d_context *current_context = context_get_current();
3472 struct wined3d_texture *target_texture;
3473 unsigned int target_sub_resource_idx;
3474 struct wined3d_context *context;
3476 TRACE("device %p, target %p.\n", device, target);
3478 if (current_context && current_context->destroyed)
3479 current_context = NULL;
3481 if (target)
3483 target_texture = target->container;
3484 target_sub_resource_idx = surface_get_sub_resource_idx(target);
3486 else
3488 if (current_context
3489 && current_context->current_rt.texture
3490 && current_context->swapchain->device == device)
3492 target_texture = current_context->current_rt.texture;
3493 target_sub_resource_idx = current_context->current_rt.sub_resource_idx;
3495 else
3497 struct wined3d_swapchain *swapchain = device->swapchains[0];
3499 if (swapchain->back_buffers)
3500 target_texture = swapchain->back_buffers[0];
3501 else
3502 target_texture = swapchain->front_buffer;
3503 target_sub_resource_idx = 0;
3507 if (current_context && current_context->current_rt.texture == target_texture)
3509 context = current_context;
3511 else if (target_texture->swapchain)
3513 TRACE("Rendering onscreen.\n");
3515 context = swapchain_get_context(target_texture->swapchain);
3517 else
3519 TRACE("Rendering offscreen.\n");
3521 /* Stay with the current context if possible. Otherwise use the
3522 * context for the primary swapchain. */
3523 if (current_context && current_context->swapchain->device == device)
3524 context = current_context;
3525 else
3526 context = swapchain_get_context(device->swapchains[0]);
3529 context_enter(context);
3530 context_update_window(context);
3531 context_setup_target(context, target_texture, target_sub_resource_idx);
3532 if (!context->valid) return context;
3534 if (context != current_context)
3536 if (!context_set_current(context))
3537 ERR("Failed to activate the new context.\n");
3539 else if (context->needs_set)
3541 context_set_gl_context(context);
3544 return context;