wined3d: Initialise stream frequency to 1.
[wine.git] / dlls / wined3d / context.c
blob96ba06ddf1ce47b3a22cf255a19c1bfa1e5652d4
1 /*
2 * Context and render target management in wined3d
4 * Copyright 2002-2004 Jason Edmeades
5 * Copyright 2002-2004 Raphael Junqueira
6 * Copyright 2004 Christian Costa
7 * Copyright 2005 Oliver Stieber
8 * Copyright 2006, 2008 Henri Verbeet
9 * Copyright 2007-2011, 2013 Stefan Dösinger for CodeWeavers
10 * Copyright 2009-2011 Henri Verbeet for CodeWeavers
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 #include "config.h"
28 #include "wine/port.h"
30 #include <stdio.h>
31 #ifdef HAVE_FLOAT_H
32 # include <float.h>
33 #endif
35 #include "wined3d_private.h"
37 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_perf);
39 WINE_DECLARE_DEBUG_CHANNEL(d3d_synchronous);
41 #define WINED3D_MAX_FBO_ENTRIES 64
42 #define WINED3D_ALL_LAYERS (~0u)
44 static DWORD wined3d_context_tls_idx;
46 /* FBO helper functions */
48 /* Context activation is done by the caller. */
49 static void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint fbo)
51 const struct wined3d_gl_info *gl_info = context->gl_info;
53 switch (target)
55 case GL_READ_FRAMEBUFFER:
56 if (context->fbo_read_binding == fbo) return;
57 context->fbo_read_binding = fbo;
58 break;
60 case GL_DRAW_FRAMEBUFFER:
61 if (context->fbo_draw_binding == fbo) return;
62 context->fbo_draw_binding = fbo;
63 break;
65 case GL_FRAMEBUFFER:
66 if (context->fbo_read_binding == fbo
67 && context->fbo_draw_binding == fbo) return;
68 context->fbo_read_binding = fbo;
69 context->fbo_draw_binding = fbo;
70 break;
72 default:
73 FIXME("Unhandled target %#x.\n", target);
74 break;
77 gl_info->fbo_ops.glBindFramebuffer(target, fbo);
78 checkGLcall("glBindFramebuffer()");
81 /* Context activation is done by the caller. */
82 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info, GLenum target)
84 unsigned int i;
86 for (i = 0; i < gl_info->limits.buffers; ++i)
88 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
89 checkGLcall("glFramebufferTexture2D()");
91 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
92 checkGLcall("glFramebufferTexture2D()");
94 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
95 checkGLcall("glFramebufferTexture2D()");
98 /* Context activation is done by the caller. */
99 static void context_destroy_fbo(struct wined3d_context *context, GLuint fbo)
101 const struct wined3d_gl_info *gl_info = context->gl_info;
103 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
104 context_clean_fbo_attachments(gl_info, GL_FRAMEBUFFER);
105 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
107 gl_info->fbo_ops.glDeleteFramebuffers(1, &fbo);
108 checkGLcall("glDeleteFramebuffers()");
111 static void context_attach_depth_stencil_rb(const struct wined3d_gl_info *gl_info,
112 GLenum fbo_target, DWORD flags, GLuint rb)
114 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
116 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
117 checkGLcall("glFramebufferRenderbuffer()");
120 if (flags & WINED3D_FBO_ENTRY_FLAG_STENCIL)
122 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb);
123 checkGLcall("glFramebufferRenderbuffer()");
127 static void context_attach_gl_texture_fbo(struct wined3d_context *context,
128 GLenum fbo_target, GLenum attachment, const struct wined3d_fbo_resource *resource)
130 const struct wined3d_gl_info *gl_info = context->gl_info;
132 if (!resource)
134 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, attachment, GL_TEXTURE_2D, 0, 0);
136 else if (resource->layer == WINED3D_ALL_LAYERS)
138 if (!gl_info->fbo_ops.glFramebufferTexture)
140 FIXME("OpenGL implementation doesn't support glFramebufferTexture().\n");
141 return;
144 gl_info->fbo_ops.glFramebufferTexture(fbo_target, attachment,
145 resource->object, resource->level);
147 else if (resource->target == GL_TEXTURE_1D_ARRAY || resource->target == GL_TEXTURE_2D_ARRAY
148 || resource->target == GL_TEXTURE_3D)
150 if (!gl_info->fbo_ops.glFramebufferTextureLayer)
152 FIXME("OpenGL implementation doesn't support glFramebufferTextureLayer().\n");
153 return;
156 gl_info->fbo_ops.glFramebufferTextureLayer(fbo_target, attachment,
157 resource->object, resource->level, resource->layer);
159 else if (resource->target == GL_TEXTURE_1D)
161 gl_info->fbo_ops.glFramebufferTexture1D(fbo_target, attachment,
162 resource->target, resource->object, resource->level);
164 else
166 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, attachment,
167 resource->target, resource->object, resource->level);
169 checkGLcall("attach texture to fbo");
172 /* Context activation is done by the caller. */
173 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
174 GLenum fbo_target, const struct wined3d_fbo_resource *resource, BOOL rb_namespace,
175 DWORD flags)
177 const struct wined3d_gl_info *gl_info = context->gl_info;
179 if (resource->object)
181 TRACE("Attach depth stencil %u.\n", resource->object);
183 if (rb_namespace)
185 context_attach_depth_stencil_rb(gl_info, fbo_target,
186 flags, resource->object);
188 else
190 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
191 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, resource);
193 if (flags & WINED3D_FBO_ENTRY_FLAG_STENCIL)
194 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, resource);
197 if (!(flags & WINED3D_FBO_ENTRY_FLAG_DEPTH))
198 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, NULL);
200 if (!(flags & WINED3D_FBO_ENTRY_FLAG_STENCIL))
201 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, NULL);
203 else
205 TRACE("Attach depth stencil 0.\n");
207 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, NULL);
208 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, NULL);
212 /* Context activation is done by the caller. */
213 static void context_attach_surface_fbo(struct wined3d_context *context,
214 GLenum fbo_target, DWORD idx, const struct wined3d_fbo_resource *resource, BOOL rb_namespace)
216 const struct wined3d_gl_info *gl_info = context->gl_info;
218 TRACE("Attach GL object %u to %u.\n", resource->object, idx);
220 if (resource->object)
222 if (rb_namespace)
224 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
225 GL_RENDERBUFFER, resource->object);
226 checkGLcall("glFramebufferRenderbuffer()");
228 else
230 context_attach_gl_texture_fbo(context, fbo_target, GL_COLOR_ATTACHMENT0 + idx, resource);
233 else
235 context_attach_gl_texture_fbo(context, fbo_target, GL_COLOR_ATTACHMENT0 + idx, NULL);
239 static void context_dump_fbo_attachment(const struct wined3d_gl_info *gl_info, GLenum target,
240 GLenum attachment)
242 static const struct
244 GLenum target;
245 GLenum binding;
246 const char *str;
247 enum wined3d_gl_extension extension;
249 texture_type[] =
251 {GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D, "1d", WINED3D_GL_EXT_NONE},
252 {GL_TEXTURE_1D_ARRAY, GL_TEXTURE_BINDING_1D_ARRAY, "1d-array", EXT_TEXTURE_ARRAY},
253 {GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D, "2d", WINED3D_GL_EXT_NONE},
254 {GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_BINDING_RECTANGLE_ARB, "rectangle", ARB_TEXTURE_RECTANGLE},
255 {GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BINDING_2D_ARRAY, "2d-array" , EXT_TEXTURE_ARRAY},
256 {GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP, "cube", ARB_TEXTURE_CUBE_MAP},
257 {GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_BINDING_2D_MULTISAMPLE, "2d-ms", ARB_TEXTURE_MULTISAMPLE},
258 {GL_TEXTURE_2D_MULTISAMPLE_ARRAY, GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY, "2d-array-ms", ARB_TEXTURE_MULTISAMPLE},
261 GLint type, name, samples, width, height, old_texture, level, face, fmt, tex_target;
262 const char *tex_type_str;
263 unsigned int i;
265 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
266 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &name);
267 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
268 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);
270 if (type == GL_RENDERBUFFER)
272 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, name);
273 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
274 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
275 if (gl_info->limits.samples > 1)
276 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
277 else
278 samples = 1;
279 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &fmt);
280 FIXME(" %s: renderbuffer %d, %dx%d, %d samples, format %#x.\n",
281 debug_fboattachment(attachment), name, width, height, samples, fmt);
283 else if (type == GL_TEXTURE)
285 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
286 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &level);
287 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
288 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, &face);
290 if (gl_info->gl_ops.ext.p_glGetTextureParameteriv)
292 GL_EXTCALL(glGetTextureParameteriv(name, GL_TEXTURE_TARGET, &tex_target));
294 for (i = 0; i < ARRAY_SIZE(texture_type); ++i)
296 if (texture_type[i].target == tex_target)
298 tex_type_str = texture_type[i].str;
299 break;
302 if (i == ARRAY_SIZE(texture_type))
303 tex_type_str = wine_dbg_sprintf("%#x", tex_target);
305 else if (face)
307 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &old_texture);
308 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, name);
310 tex_target = GL_TEXTURE_CUBE_MAP;
311 tex_type_str = "cube";
313 else
315 tex_type_str = NULL;
317 for (i = 0; i < ARRAY_SIZE(texture_type); ++i)
319 if (!gl_info->supported[texture_type[i].extension])
320 continue;
322 gl_info->gl_ops.gl.p_glGetIntegerv(texture_type[i].binding, &old_texture);
323 while (gl_info->gl_ops.gl.p_glGetError());
325 gl_info->gl_ops.gl.p_glBindTexture(texture_type[i].target, name);
326 if (!gl_info->gl_ops.gl.p_glGetError())
328 tex_target = texture_type[i].target;
329 tex_type_str = texture_type[i].str;
330 break;
332 gl_info->gl_ops.gl.p_glBindTexture(texture_type[i].target, old_texture);
335 if (!tex_type_str)
337 FIXME("Cannot find type of texture %d.\n", name);
338 return;
342 if (gl_info->gl_ops.ext.p_glGetTextureParameteriv)
344 GL_EXTCALL(glGetTextureLevelParameteriv(name, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt));
345 GL_EXTCALL(glGetTextureLevelParameteriv(name, level, GL_TEXTURE_WIDTH, &width));
346 GL_EXTCALL(glGetTextureLevelParameteriv(name, level, GL_TEXTURE_HEIGHT, &height));
347 GL_EXTCALL(glGetTextureLevelParameteriv(name, level, GL_TEXTURE_SAMPLES, &samples));
349 else
351 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
352 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_WIDTH, &width);
353 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_HEIGHT, &height);
354 if (gl_info->supported[ARB_TEXTURE_MULTISAMPLE])
355 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_SAMPLES, &samples);
356 else
357 samples = 1;
359 gl_info->gl_ops.gl.p_glBindTexture(tex_target, old_texture);
362 FIXME(" %s: %s texture %d, %dx%d, %d samples, format %#x.\n",
363 debug_fboattachment(attachment), tex_type_str, name, width, height, samples, fmt);
365 else if (type == GL_NONE)
367 FIXME(" %s: NONE.\n", debug_fboattachment(attachment));
369 else
371 ERR(" %s: Unknown attachment %#x.\n", debug_fboattachment(attachment), type);
374 checkGLcall("dump FBO attachment");
377 /* Context activation is done by the caller. */
378 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
380 const struct wined3d_gl_info *gl_info = context->gl_info;
381 GLenum status;
383 if (!FIXME_ON(d3d))
384 return;
386 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
387 if (status == GL_FRAMEBUFFER_COMPLETE)
389 TRACE("FBO complete.\n");
391 else
393 unsigned int i;
395 FIXME("FBO status %s (%#x).\n", debug_fbostatus(status), status);
397 if (!context->current_fbo)
399 ERR("FBO 0 is incomplete, driver bug?\n");
400 return;
403 context_dump_fbo_attachment(gl_info, target, GL_DEPTH_ATTACHMENT);
404 context_dump_fbo_attachment(gl_info, target, GL_STENCIL_ATTACHMENT);
406 for (i = 0; i < gl_info->limits.buffers; ++i)
407 context_dump_fbo_attachment(gl_info, target, GL_COLOR_ATTACHMENT0 + i);
411 static inline DWORD context_generate_rt_mask(GLenum buffer)
413 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
414 return buffer ? (1u << 31) | buffer : 0;
417 static inline DWORD context_generate_rt_mask_from_resource(struct wined3d_resource *resource)
419 if (resource->type != WINED3D_RTYPE_TEXTURE_2D)
421 FIXME("Not implemented for %s resources.\n", debug_d3dresourcetype(resource->type));
422 return 0;
425 return (1u << 31) | wined3d_texture_get_gl_buffer(texture_from_resource(resource));
428 static inline void context_set_fbo_key_for_render_target(const struct wined3d_context *context,
429 struct wined3d_fbo_entry_key *key, unsigned int idx, const struct wined3d_rendertarget_info *render_target,
430 DWORD location)
432 unsigned int sub_resource_idx = render_target->sub_resource_idx;
433 struct wined3d_resource *resource = render_target->resource;
434 struct wined3d_texture_gl *texture_gl;
436 if (!resource || resource->format->id == WINED3DFMT_NULL || resource->type == WINED3D_RTYPE_BUFFER)
438 if (resource && resource->type == WINED3D_RTYPE_BUFFER)
439 FIXME("Not implemented for %s resources.\n", debug_d3dresourcetype(resource->type));
440 key->objects[idx].object = 0;
441 key->objects[idx].target = 0;
442 key->objects[idx].level = key->objects[idx].layer = 0;
443 return;
446 if (render_target->gl_view.name)
448 key->objects[idx].object = render_target->gl_view.name;
449 key->objects[idx].target = render_target->gl_view.target;
450 key->objects[idx].level = 0;
451 key->objects[idx].layer = WINED3D_ALL_LAYERS;
452 return;
455 texture_gl = wined3d_texture_gl(wined3d_texture_from_resource(resource));
456 if (texture_gl->current_renderbuffer)
458 key->objects[idx].object = texture_gl->current_renderbuffer->id;
459 key->objects[idx].target = 0;
460 key->objects[idx].level = key->objects[idx].layer = 0;
461 key->rb_namespace |= 1 << idx;
462 return;
465 key->objects[idx].target = wined3d_texture_gl_get_sub_resource_target(texture_gl, sub_resource_idx);
466 key->objects[idx].level = sub_resource_idx % texture_gl->t.level_count;
467 key->objects[idx].layer = sub_resource_idx / texture_gl->t.level_count;
469 if (render_target->layer_count != 1)
470 key->objects[idx].layer = WINED3D_ALL_LAYERS;
472 switch (location)
474 case WINED3D_LOCATION_TEXTURE_RGB:
475 key->objects[idx].object = wined3d_texture_gl_get_texture_name(texture_gl, context, FALSE);
476 break;
478 case WINED3D_LOCATION_TEXTURE_SRGB:
479 key->objects[idx].object = wined3d_texture_gl_get_texture_name(texture_gl, context, TRUE);
480 break;
482 case WINED3D_LOCATION_RB_MULTISAMPLE:
483 key->objects[idx].object = texture_gl->rb_multisample;
484 key->objects[idx].target = 0;
485 key->objects[idx].level = key->objects[idx].layer = 0;
486 key->rb_namespace |= 1 << idx;
487 break;
489 case WINED3D_LOCATION_RB_RESOLVED:
490 key->objects[idx].object = texture_gl->rb_resolved;
491 key->objects[idx].target = 0;
492 key->objects[idx].level = key->objects[idx].layer = 0;
493 key->rb_namespace |= 1 << idx;
494 break;
498 static void context_generate_fbo_key(const struct wined3d_context *context,
499 struct wined3d_fbo_entry_key *key, const struct wined3d_rendertarget_info *render_targets,
500 const struct wined3d_rendertarget_info *depth_stencil, DWORD color_location, DWORD ds_location)
502 unsigned int buffers = context->gl_info->limits.buffers;
503 unsigned int i;
505 key->rb_namespace = 0;
506 context_set_fbo_key_for_render_target(context, key, 0, depth_stencil, ds_location);
508 for (i = 0; i < buffers; ++i)
509 context_set_fbo_key_for_render_target(context, key, i + 1, &render_targets[i], color_location);
511 memset(&key->objects[buffers + 1], 0, (ARRAY_SIZE(key->objects) - buffers - 1) * sizeof(*key->objects));
514 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
515 const struct wined3d_rendertarget_info *render_targets, const struct wined3d_rendertarget_info *depth_stencil,
516 DWORD color_location, DWORD ds_location)
518 const struct wined3d_gl_info *gl_info = context->gl_info;
519 struct fbo_entry *entry;
521 entry = heap_alloc(sizeof(*entry));
522 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
523 entry->flags = 0;
524 if (depth_stencil->resource)
526 if (depth_stencil->resource->format_flags & WINED3DFMT_FLAG_DEPTH)
527 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
528 if (depth_stencil->resource->format_flags & WINED3DFMT_FLAG_STENCIL)
529 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
531 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
532 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
533 checkGLcall("glGenFramebuffers()");
534 TRACE("Created FBO %u.\n", entry->id);
536 return entry;
539 /* Context activation is done by the caller. */
540 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
541 const struct wined3d_rendertarget_info *render_targets, const struct wined3d_rendertarget_info *depth_stencil,
542 DWORD color_location, DWORD ds_location, struct fbo_entry *entry)
544 const struct wined3d_gl_info *gl_info = context->gl_info;
546 context_bind_fbo(context, target, entry->id);
547 context_clean_fbo_attachments(gl_info, target);
549 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
550 entry->flags = 0;
551 if (depth_stencil->resource)
553 if (depth_stencil->resource->format_flags & WINED3DFMT_FLAG_DEPTH)
554 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
555 if (depth_stencil->resource->format_flags & WINED3DFMT_FLAG_STENCIL)
556 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
560 /* Context activation is done by the caller. */
561 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
563 if (entry->id)
565 TRACE("Destroy FBO %u.\n", entry->id);
566 context_destroy_fbo(context, entry->id);
568 --context->fbo_entry_count;
569 list_remove(&entry->entry);
570 heap_free(entry);
573 /* Context activation is done by the caller. */
574 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
575 const struct wined3d_rendertarget_info *render_targets, const struct wined3d_rendertarget_info *depth_stencil,
576 DWORD color_location, DWORD ds_location)
578 static const struct wined3d_rendertarget_info ds_null = {{0}};
579 const struct wined3d_gl_info *gl_info = context->gl_info;
580 struct wined3d_texture *rt_texture, *ds_texture;
581 struct wined3d_fbo_entry_key fbo_key;
582 unsigned int i, ds_level, rt_level;
583 struct fbo_entry *entry;
585 if (depth_stencil->resource && depth_stencil->resource->type != WINED3D_RTYPE_BUFFER
586 && render_targets[0].resource && render_targets[0].resource->type != WINED3D_RTYPE_BUFFER)
588 rt_texture = wined3d_texture_from_resource(render_targets[0].resource);
589 rt_level = render_targets[0].sub_resource_idx % rt_texture->level_count;
590 ds_texture = wined3d_texture_from_resource(depth_stencil->resource);
591 ds_level = depth_stencil->sub_resource_idx % ds_texture->level_count;
593 if (wined3d_texture_get_level_width(ds_texture, ds_level)
594 < wined3d_texture_get_level_width(rt_texture, rt_level)
595 || wined3d_texture_get_level_height(ds_texture, ds_level)
596 < wined3d_texture_get_level_height(rt_texture, rt_level))
598 WARN("Depth stencil is smaller than the primary color buffer, disabling.\n");
599 depth_stencil = &ds_null;
601 else if (ds_texture->resource.multisample_type != rt_texture->resource.multisample_type
602 || (ds_texture->resource.multisample_type
603 && ds_texture->resource.multisample_quality != rt_texture->resource.multisample_quality))
605 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
606 rt_texture->resource.multisample_type, rt_texture->resource.multisample_quality,
607 ds_texture->resource.multisample_type, ds_texture->resource.multisample_quality);
608 depth_stencil = &ds_null;
610 else if (depth_stencil->resource->type == WINED3D_RTYPE_TEXTURE_2D)
612 wined3d_texture_gl_set_compatible_renderbuffer(wined3d_texture_gl(ds_texture),
613 context, ds_level, &render_targets[0]);
617 context_generate_fbo_key(context, &fbo_key, render_targets, depth_stencil, color_location, ds_location);
619 if (TRACE_ON(d3d))
621 struct wined3d_resource *resource;
622 unsigned int width, height;
623 const char *resource_type;
625 TRACE("Dumping FBO attachments:\n");
626 for (i = 0; i < gl_info->limits.buffers; ++i)
628 if ((resource = render_targets[i].resource))
630 if (resource->type == WINED3D_RTYPE_BUFFER)
632 width = resource->size;
633 height = 1;
634 resource_type = "buffer";
636 else
638 rt_texture = wined3d_texture_from_resource(resource);
639 rt_level = render_targets[i].sub_resource_idx % rt_texture->level_count;
640 width = wined3d_texture_get_level_pow2_width(rt_texture, rt_level);
641 height = wined3d_texture_get_level_pow2_height(rt_texture, rt_level);
642 resource_type = "texture";
645 TRACE(" Color attachment %u: %p, %u format %s, %s %u, %ux%u, %u samples.\n",
646 i, resource, render_targets[i].sub_resource_idx, debug_d3dformat(resource->format->id),
647 fbo_key.rb_namespace & (1 << (i + 1)) ? "renderbuffer" : resource_type,
648 fbo_key.objects[i + 1].object, width, height, resource->multisample_type);
651 if ((resource = depth_stencil->resource))
653 if (resource->type == WINED3D_RTYPE_BUFFER)
655 width = resource->size;
656 height = 1;
657 resource_type = "buffer";
659 else
661 ds_texture = wined3d_texture_from_resource(resource);
662 ds_level = depth_stencil->sub_resource_idx % ds_texture->level_count;
663 width = wined3d_texture_get_level_pow2_width(ds_texture, ds_level);
664 height = wined3d_texture_get_level_pow2_height(ds_texture, ds_level);
665 resource_type = "texture";
668 TRACE(" Depth attachment: %p, %u format %s, %s %u, %ux%u, %u samples.\n",
669 resource, depth_stencil->sub_resource_idx, debug_d3dformat(resource->format->id),
670 fbo_key.rb_namespace & (1 << 0) ? "renderbuffer" : resource_type,
671 fbo_key.objects[0].object, width, height, resource->multisample_type);
675 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
677 if (memcmp(&fbo_key, &entry->key, sizeof(fbo_key)))
678 continue;
680 list_remove(&entry->entry);
681 list_add_head(&context->fbo_list, &entry->entry);
682 return entry;
685 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
687 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
688 list_add_head(&context->fbo_list, &entry->entry);
689 ++context->fbo_entry_count;
691 else
693 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
694 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
695 list_remove(&entry->entry);
696 list_add_head(&context->fbo_list, &entry->entry);
699 return entry;
702 /* Context activation is done by the caller. */
703 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
705 const struct wined3d_gl_info *gl_info = context->gl_info;
706 GLuint read_binding, draw_binding;
707 unsigned int i;
709 if (entry->flags & WINED3D_FBO_ENTRY_FLAG_ATTACHED)
711 context_bind_fbo(context, target, entry->id);
712 return;
715 read_binding = context->fbo_read_binding;
716 draw_binding = context->fbo_draw_binding;
717 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
719 if (gl_info->supported[ARB_FRAMEBUFFER_NO_ATTACHMENTS])
721 GL_EXTCALL(glFramebufferParameteri(GL_FRAMEBUFFER,
722 GL_FRAMEBUFFER_DEFAULT_WIDTH, gl_info->limits.framebuffer_width));
723 GL_EXTCALL(glFramebufferParameteri(GL_FRAMEBUFFER,
724 GL_FRAMEBUFFER_DEFAULT_HEIGHT, gl_info->limits.framebuffer_height));
725 GL_EXTCALL(glFramebufferParameteri(GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_LAYERS, 1));
726 GL_EXTCALL(glFramebufferParameteri(GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_SAMPLES, 1));
729 /* Apply render targets */
730 for (i = 0; i < gl_info->limits.buffers; ++i)
732 context_attach_surface_fbo(context, target, i, &entry->key.objects[i + 1],
733 entry->key.rb_namespace & (1 << (i + 1)));
736 context_attach_depth_stencil_fbo(context, target, &entry->key.objects[0],
737 entry->key.rb_namespace & 0x1, entry->flags);
739 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
740 * GL contexts requirements. */
741 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
742 context_set_draw_buffer(context, GL_NONE);
743 if (target != GL_FRAMEBUFFER)
745 if (target == GL_READ_FRAMEBUFFER)
746 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
747 else
748 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
751 entry->flags |= WINED3D_FBO_ENTRY_FLAG_ATTACHED;
754 /* Context activation is done by the caller. */
755 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
756 const struct wined3d_rendertarget_info *render_targets,
757 const struct wined3d_rendertarget_info *depth_stencil, DWORD color_location, DWORD ds_location)
759 struct fbo_entry *entry, *entry2;
761 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
763 context_destroy_fbo_entry(context, entry);
766 if (context->rebind_fbo)
768 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
769 context->rebind_fbo = FALSE;
772 if (color_location == WINED3D_LOCATION_DRAWABLE)
774 context->current_fbo = NULL;
775 context_bind_fbo(context, target, 0);
777 else
779 context->current_fbo = context_find_fbo_entry(context, target,
780 render_targets, depth_stencil, color_location, ds_location);
781 context_apply_fbo_entry(context, target, context->current_fbo);
785 /* Context activation is done by the caller. */
786 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
787 struct wined3d_resource *rt, unsigned int rt_sub_resource_idx,
788 struct wined3d_resource *ds, unsigned int ds_sub_resource_idx, DWORD location)
790 struct wined3d_rendertarget_info ds_info = {{0}};
792 memset(context->blit_targets, 0, sizeof(context->blit_targets));
793 if (rt)
795 context->blit_targets[0].resource = rt;
796 context->blit_targets[0].sub_resource_idx = rt_sub_resource_idx;
797 context->blit_targets[0].layer_count = 1;
800 if (ds)
802 ds_info.resource = ds;
803 ds_info.sub_resource_idx = ds_sub_resource_idx;
804 ds_info.layer_count = 1;
807 context_apply_fbo_state(context, target, context->blit_targets, &ds_info, location, location);
810 /* Context activation is done by the caller. */
811 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
813 const struct wined3d_gl_info *gl_info = context->gl_info;
815 if (context->free_occlusion_query_count)
817 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
819 else
821 if (gl_info->supported[ARB_OCCLUSION_QUERY])
823 GL_EXTCALL(glGenQueries(1, &query->id));
824 checkGLcall("glGenQueries");
826 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
828 else
830 WARN("Occlusion queries not supported, not allocating query id.\n");
831 query->id = 0;
835 query->context = context;
836 list_add_head(&context->occlusion_queries, &query->entry);
839 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
841 struct wined3d_context *context = query->context;
843 list_remove(&query->entry);
844 query->context = NULL;
846 if (!wined3d_array_reserve((void **)&context->free_occlusion_queries,
847 &context->free_occlusion_query_size, context->free_occlusion_query_count + 1,
848 sizeof(*context->free_occlusion_queries)))
850 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
851 return;
854 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
857 /* Context activation is done by the caller. */
858 void context_alloc_fence(struct wined3d_context *context, struct wined3d_fence *fence)
860 const struct wined3d_gl_info *gl_info = context->gl_info;
862 if (context->free_fence_count)
864 fence->object = context->free_fences[--context->free_fence_count];
866 else
868 if (gl_info->supported[ARB_SYNC])
870 /* Using ARB_sync, not much to do here. */
871 fence->object.sync = NULL;
872 TRACE("Allocated sync object in context %p.\n", context);
874 else if (gl_info->supported[APPLE_FENCE])
876 GL_EXTCALL(glGenFencesAPPLE(1, &fence->object.id));
877 checkGLcall("glGenFencesAPPLE");
879 TRACE("Allocated fence %u in context %p.\n", fence->object.id, context);
881 else if(gl_info->supported[NV_FENCE])
883 GL_EXTCALL(glGenFencesNV(1, &fence->object.id));
884 checkGLcall("glGenFencesNV");
886 TRACE("Allocated fence %u in context %p.\n", fence->object.id, context);
888 else
890 WARN("Fences not supported, not allocating fence.\n");
891 fence->object.id = 0;
895 fence->context = context;
896 list_add_head(&context->fences, &fence->entry);
899 void context_free_fence(struct wined3d_fence *fence)
901 struct wined3d_context *context = fence->context;
903 list_remove(&fence->entry);
904 fence->context = NULL;
906 if (!wined3d_array_reserve((void **)&context->free_fences,
907 &context->free_fence_size, context->free_fence_count + 1,
908 sizeof(*context->free_fences)))
910 ERR("Failed to grow free list, leaking fence %u in context %p.\n", fence->object.id, context);
911 return;
914 context->free_fences[context->free_fence_count++] = fence->object;
917 /* Context activation is done by the caller. */
918 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
920 const struct wined3d_gl_info *gl_info = context->gl_info;
922 if (context->free_timestamp_query_count)
924 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
926 else
928 GL_EXTCALL(glGenQueries(1, &query->id));
929 checkGLcall("glGenQueries");
931 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
934 query->context = context;
935 list_add_head(&context->timestamp_queries, &query->entry);
938 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
940 struct wined3d_context *context = query->context;
942 list_remove(&query->entry);
943 query->context = NULL;
945 if (!wined3d_array_reserve((void **)&context->free_timestamp_queries,
946 &context->free_timestamp_query_size, context->free_timestamp_query_count + 1,
947 sizeof(*context->free_timestamp_queries)))
949 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
950 return;
953 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
956 void context_alloc_so_statistics_query(struct wined3d_context *context,
957 struct wined3d_so_statistics_query *query)
959 const struct wined3d_gl_info *gl_info = context->gl_info;
961 if (context->free_so_statistics_query_count)
963 query->u = context->free_so_statistics_queries[--context->free_so_statistics_query_count];
965 else
967 GL_EXTCALL(glGenQueries(ARRAY_SIZE(query->u.id), query->u.id));
968 checkGLcall("glGenQueries");
970 TRACE("Allocated SO statistics queries %u, %u in context %p.\n",
971 query->u.id[0], query->u.id[1], context);
974 query->context = context;
975 list_add_head(&context->so_statistics_queries, &query->entry);
978 void context_free_so_statistics_query(struct wined3d_so_statistics_query *query)
980 struct wined3d_context *context = query->context;
982 list_remove(&query->entry);
983 query->context = NULL;
985 if (!wined3d_array_reserve((void **)&context->free_so_statistics_queries,
986 &context->free_so_statistics_query_size, context->free_so_statistics_query_count + 1,
987 sizeof(*context->free_so_statistics_queries)))
989 ERR("Failed to grow free list, leaking GL queries %u, %u in context %p.\n",
990 query->u.id[0], query->u.id[1], context);
991 return;
994 context->free_so_statistics_queries[context->free_so_statistics_query_count++] = query->u;
997 void context_alloc_pipeline_statistics_query(struct wined3d_context *context,
998 struct wined3d_pipeline_statistics_query *query)
1000 const struct wined3d_gl_info *gl_info = context->gl_info;
1002 if (context->free_pipeline_statistics_query_count)
1004 query->u = context->free_pipeline_statistics_queries[--context->free_pipeline_statistics_query_count];
1006 else
1008 GL_EXTCALL(glGenQueries(ARRAY_SIZE(query->u.id), query->u.id));
1009 checkGLcall("glGenQueries");
1012 query->context = context;
1013 list_add_head(&context->pipeline_statistics_queries, &query->entry);
1016 void context_free_pipeline_statistics_query(struct wined3d_pipeline_statistics_query *query)
1018 struct wined3d_context *context = query->context;
1020 list_remove(&query->entry);
1021 query->context = NULL;
1023 if (!wined3d_array_reserve((void **)&context->free_pipeline_statistics_queries,
1024 &context->free_pipeline_statistics_query_size, context->free_pipeline_statistics_query_count + 1,
1025 sizeof(*context->free_pipeline_statistics_queries)))
1027 ERR("Failed to grow free list, leaking GL queries in context %p.\n", context);
1028 return;
1031 context->free_pipeline_statistics_queries[context->free_pipeline_statistics_query_count++] = query->u;
1034 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
1036 static void context_enum_fbo_entries(const struct wined3d_device *device,
1037 GLuint name, BOOL rb_namespace, context_fbo_entry_func_t *callback)
1039 unsigned int i, j;
1041 for (i = 0; i < device->context_count; ++i)
1043 struct wined3d_context *context = device->contexts[i];
1044 const struct wined3d_gl_info *gl_info = context->gl_info;
1045 struct fbo_entry *entry, *entry2;
1047 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1049 for (j = 0; j < gl_info->limits.buffers + 1; ++j)
1051 if (entry->key.objects[j].object == name
1052 && !(entry->key.rb_namespace & (1 << j)) == !rb_namespace)
1054 callback(context, entry);
1055 break;
1062 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
1064 list_remove(&entry->entry);
1065 list_add_head(&context->fbo_destroy_list, &entry->entry);
1068 void context_resource_released(const struct wined3d_device *device, struct wined3d_resource *resource)
1070 unsigned int i;
1072 if (!device->d3d_initialized)
1073 return;
1075 for (i = 0; i < device->context_count; ++i)
1077 struct wined3d_context *context = device->contexts[i];
1079 if (&context->current_rt.texture->resource == resource)
1081 context->current_rt.texture = NULL;
1082 context->current_rt.sub_resource_idx = 0;
1087 void context_gl_resource_released(struct wined3d_device *device,
1088 GLuint name, BOOL rb_namespace)
1090 context_enum_fbo_entries(device, name, rb_namespace, context_queue_fbo_entry_destruction);
1093 void context_texture_update(struct wined3d_context *context, const struct wined3d_texture_gl *texture_gl)
1095 const struct wined3d_gl_info *gl_info = context->gl_info;
1096 struct fbo_entry *entry = context->current_fbo;
1097 unsigned int i;
1099 if (!entry || context->rebind_fbo) return;
1101 for (i = 0; i < gl_info->limits.buffers + 1; ++i)
1103 if (texture_gl->texture_rgb.name == entry->key.objects[i].object
1104 || texture_gl->texture_srgb.name == entry->key.objects[i].object)
1106 TRACE("Updated texture %p is bound as attachment %u to the current FBO.\n", texture_gl, i);
1107 context->rebind_fbo = TRUE;
1108 return;
1113 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
1115 const struct wined3d_gl_info *gl_info = ctx->gl_info;
1116 BOOL ret = FALSE;
1118 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
1120 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
1122 HDC dc = GetDCEx(ctx->restore_pf_win, 0, DCX_USESTYLE | DCX_CACHE);
1123 if (dc)
1125 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
1127 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
1128 ctx->restore_pf, ctx->restore_pf_win);
1130 ReleaseDC(ctx->restore_pf_win, dc);
1133 else
1135 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
1139 ctx->restore_pf = 0;
1140 ctx->restore_pf_win = NULL;
1141 return ret;
1144 static BOOL context_set_pixel_format(struct wined3d_context *context)
1146 const struct wined3d_gl_info *gl_info = context->gl_info;
1147 BOOL private = context->hdc_is_private;
1148 int format = context->pixel_format;
1149 HDC dc = context->hdc;
1150 int current;
1152 if (private && context->hdc_has_format)
1153 return TRUE;
1155 if (!private && WindowFromDC(dc) != context->win_handle)
1156 return FALSE;
1158 current = gl_info->gl_ops.wgl.p_wglGetPixelFormat(dc);
1159 if (current == format) goto success;
1161 if (!current)
1163 if (!SetPixelFormat(dc, format, NULL))
1165 /* This may also happen if the dc belongs to a destroyed window. */
1166 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
1167 format, dc, GetLastError());
1168 return FALSE;
1171 context->restore_pf = 0;
1172 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
1173 goto success;
1176 /* By default WGL doesn't allow pixel format adjustments but we need it
1177 * here. For this reason there's a Wine specific wglSetPixelFormat()
1178 * which allows us to set the pixel format multiple times. Only use it
1179 * when really needed. */
1180 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
1182 HWND win;
1184 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
1186 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
1187 format, dc);
1188 return FALSE;
1191 win = private ? NULL : WindowFromDC(dc);
1192 if (win != context->restore_pf_win)
1194 context_restore_pixel_format(context);
1196 context->restore_pf = private ? 0 : current;
1197 context->restore_pf_win = win;
1200 goto success;
1203 /* OpenGL doesn't allow pixel format adjustments. Print an error and
1204 * continue using the old format. There's a big chance that the old
1205 * format works although with a performance hit and perhaps rendering
1206 * errors. */
1207 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
1208 format, dc, current);
1209 return TRUE;
1211 success:
1212 if (private)
1213 context->hdc_has_format = TRUE;
1214 return TRUE;
1217 static BOOL context_set_gl_context(struct wined3d_context *ctx)
1219 struct wined3d_swapchain *swapchain = ctx->swapchain;
1220 BOOL backup = FALSE;
1222 if (!context_set_pixel_format(ctx))
1224 WARN("Failed to set pixel format %d on device context %p.\n",
1225 ctx->pixel_format, ctx->hdc);
1226 backup = TRUE;
1229 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
1231 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
1232 ctx->glCtx, ctx->hdc, GetLastError());
1233 ctx->valid = 0;
1234 WARN("Trying fallback to the backup window.\n");
1236 /* FIXME: If the context is destroyed it's no longer associated with
1237 * a swapchain, so we can't use the swapchain to get a backup dc. To
1238 * make this work windowless contexts would need to be handled by the
1239 * device. */
1240 if (ctx->destroyed || !swapchain)
1242 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
1243 context_set_current(NULL);
1244 return FALSE;
1247 if (!(ctx->hdc = swapchain_get_backup_dc(swapchain)))
1249 context_set_current(NULL);
1250 return FALSE;
1253 ctx->hdc_is_private = TRUE;
1254 ctx->hdc_has_format = FALSE;
1256 if (!context_set_pixel_format(ctx))
1258 ERR("Failed to set pixel format %d on device context %p.\n",
1259 ctx->pixel_format, ctx->hdc);
1260 context_set_current(NULL);
1261 return FALSE;
1264 if (!wglMakeCurrent(ctx->hdc, ctx->glCtx))
1266 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
1267 ctx->hdc, GetLastError());
1268 context_set_current(NULL);
1269 return FALSE;
1272 ctx->valid = 1;
1274 ctx->needs_set = 0;
1275 return TRUE;
1278 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
1280 if (!wglMakeCurrent(dc, gl_ctx))
1282 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1283 gl_ctx, dc, GetLastError());
1284 context_set_current(NULL);
1288 static void context_update_window(struct wined3d_context *context)
1290 if (!context->swapchain)
1291 return;
1293 if (context->win_handle == context->swapchain->win_handle)
1294 return;
1296 TRACE("Updating context %p window from %p to %p.\n",
1297 context, context->win_handle, context->swapchain->win_handle);
1299 if (context->hdc)
1300 wined3d_release_dc(context->win_handle, context->hdc);
1302 context->win_handle = context->swapchain->win_handle;
1303 context->hdc_is_private = FALSE;
1304 context->hdc_has_format = FALSE;
1305 context->needs_set = 1;
1306 context->valid = 1;
1308 if (!(context->hdc = GetDCEx(context->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1310 ERR("Failed to get a device context for window %p.\n", context->win_handle);
1311 context->valid = 0;
1315 static void context_destroy_gl_resources(struct wined3d_context *context)
1317 struct wined3d_pipeline_statistics_query *pipeline_statistics_query;
1318 const struct wined3d_gl_info *gl_info = context->gl_info;
1319 struct wined3d_so_statistics_query *so_statistics_query;
1320 struct wined3d_timestamp_query *timestamp_query;
1321 struct wined3d_occlusion_query *occlusion_query;
1322 struct fbo_entry *entry, *entry2;
1323 struct wined3d_fence *fence;
1324 HGLRC restore_ctx;
1325 HDC restore_dc;
1326 unsigned int i;
1328 restore_ctx = wglGetCurrentContext();
1329 restore_dc = wglGetCurrentDC();
1331 if (restore_ctx == context->glCtx)
1332 restore_ctx = NULL;
1333 else if (context->valid)
1334 context_set_gl_context(context);
1336 LIST_FOR_EACH_ENTRY(so_statistics_query, &context->so_statistics_queries,
1337 struct wined3d_so_statistics_query, entry)
1339 if (context->valid)
1340 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(so_statistics_query->u.id), so_statistics_query->u.id));
1341 so_statistics_query->context = NULL;
1344 LIST_FOR_EACH_ENTRY(pipeline_statistics_query, &context->pipeline_statistics_queries,
1345 struct wined3d_pipeline_statistics_query, entry)
1347 if (context->valid)
1348 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(pipeline_statistics_query->u.id), pipeline_statistics_query->u.id));
1349 pipeline_statistics_query->context = NULL;
1352 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
1354 if (context->valid)
1355 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
1356 timestamp_query->context = NULL;
1359 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1361 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1362 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1363 occlusion_query->context = NULL;
1366 LIST_FOR_EACH_ENTRY(fence, &context->fences, struct wined3d_fence, entry)
1368 if (context->valid)
1370 if (gl_info->supported[ARB_SYNC])
1372 if (fence->object.sync)
1373 GL_EXTCALL(glDeleteSync(fence->object.sync));
1375 else if (gl_info->supported[APPLE_FENCE])
1377 GL_EXTCALL(glDeleteFencesAPPLE(1, &fence->object.id));
1379 else if (gl_info->supported[NV_FENCE])
1381 GL_EXTCALL(glDeleteFencesNV(1, &fence->object.id));
1384 fence->context = NULL;
1387 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1389 if (!context->valid) entry->id = 0;
1390 context_destroy_fbo_entry(context, entry);
1393 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1395 if (!context->valid) entry->id = 0;
1396 context_destroy_fbo_entry(context, entry);
1399 if (context->valid)
1401 if (context->dummy_arbfp_prog)
1403 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1406 if (gl_info->supported[WINED3D_GL_PRIMITIVE_QUERY])
1408 for (i = 0; i < context->free_so_statistics_query_count; ++i)
1410 union wined3d_gl_so_statistics_query *q = &context->free_so_statistics_queries[i];
1411 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(q->id), q->id));
1415 if (gl_info->supported[ARB_PIPELINE_STATISTICS_QUERY])
1417 for (i = 0; i < context->free_pipeline_statistics_query_count; ++i)
1419 union wined3d_gl_pipeline_statistics_query *q = &context->free_pipeline_statistics_queries[i];
1420 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(q->id), q->id));
1424 if (gl_info->supported[ARB_TIMER_QUERY])
1425 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1427 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1428 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1430 if (gl_info->supported[ARB_SYNC])
1432 for (i = 0; i < context->free_fence_count; ++i)
1434 GL_EXTCALL(glDeleteSync(context->free_fences[i].sync));
1437 else if (gl_info->supported[APPLE_FENCE])
1439 for (i = 0; i < context->free_fence_count; ++i)
1441 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_fences[i].id));
1444 else if (gl_info->supported[NV_FENCE])
1446 for (i = 0; i < context->free_fence_count; ++i)
1448 GL_EXTCALL(glDeleteFencesNV(1, &context->free_fences[i].id));
1452 if (context->blit_vbo)
1453 GL_EXTCALL(glDeleteBuffers(1, &context->blit_vbo));
1455 checkGLcall("context cleanup");
1458 heap_free(context->free_so_statistics_queries);
1459 heap_free(context->free_pipeline_statistics_queries);
1460 heap_free(context->free_timestamp_queries);
1461 heap_free(context->free_occlusion_queries);
1462 heap_free(context->free_fences);
1464 context_restore_pixel_format(context);
1465 if (restore_ctx)
1467 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1469 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1471 ERR("Failed to disable GL context.\n");
1474 wined3d_release_dc(context->win_handle, context->hdc);
1476 if (!wglDeleteContext(context->glCtx))
1478 DWORD err = GetLastError();
1479 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1483 DWORD context_get_tls_idx(void)
1485 return wined3d_context_tls_idx;
1488 void context_set_tls_idx(DWORD idx)
1490 wined3d_context_tls_idx = idx;
1493 struct wined3d_context *context_get_current(void)
1495 return TlsGetValue(wined3d_context_tls_idx);
1498 BOOL context_set_current(struct wined3d_context *ctx)
1500 struct wined3d_context *old = context_get_current();
1502 if (old == ctx)
1504 TRACE("Already using D3D context %p.\n", ctx);
1505 return TRUE;
1508 if (old)
1510 if (old->destroyed)
1512 TRACE("Switching away from destroyed context %p.\n", old);
1513 context_destroy_gl_resources(old);
1514 heap_free((void *)old->gl_info);
1515 heap_free(old);
1517 else
1519 if (wglGetCurrentContext())
1521 const struct wined3d_gl_info *gl_info = old->gl_info;
1522 TRACE("Flushing context %p before switching to %p.\n", old, ctx);
1523 gl_info->gl_ops.gl.p_glFlush();
1525 old->current = 0;
1529 if (ctx)
1531 if (!ctx->valid)
1533 ERR("Trying to make invalid context %p current\n", ctx);
1534 return FALSE;
1537 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1538 if (!context_set_gl_context(ctx))
1539 return FALSE;
1540 ctx->current = 1;
1542 else if (wglGetCurrentContext())
1544 TRACE("Clearing current D3D context.\n");
1545 if (!wglMakeCurrent(NULL, NULL))
1547 DWORD err = GetLastError();
1548 ERR("Failed to clear current GL context, last error %#x.\n", err);
1549 TlsSetValue(wined3d_context_tls_idx, NULL);
1550 return FALSE;
1554 return TlsSetValue(wined3d_context_tls_idx, ctx);
1557 void context_release(struct wined3d_context *context)
1559 TRACE("Releasing context %p, level %u.\n", context, context->level);
1561 if (WARN_ON(d3d))
1563 if (!context->level)
1564 WARN("Context %p is not active.\n", context);
1565 else if (context != context_get_current())
1566 WARN("Context %p is not the current context.\n", context);
1569 if (!--context->level)
1571 if (context_restore_pixel_format(context))
1572 context->needs_set = 1;
1573 if (context->restore_ctx)
1575 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1576 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1577 context->restore_ctx = NULL;
1578 context->restore_dc = NULL;
1581 if (context->destroy_delayed)
1583 TRACE("Destroying context %p.\n", context);
1584 context_destroy(context->device, context);
1589 /* This is used when a context for render target A is active, but a separate context is
1590 * needed to access the WGL framebuffer for render target B. Re-acquire a context for rt
1591 * A to avoid breaking caller code. */
1592 void context_restore(struct wined3d_context *context, struct wined3d_texture *texture, unsigned int sub_resource_idx)
1594 if (context->current_rt.texture != texture || context->current_rt.sub_resource_idx != sub_resource_idx)
1596 context_release(context);
1597 context = context_acquire(texture->resource.device, texture, sub_resource_idx);
1600 context_release(context);
1603 static void context_enter(struct wined3d_context *context)
1605 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1607 if (!context->level++)
1609 const struct wined3d_context *current_context = context_get_current();
1610 HGLRC current_gl = wglGetCurrentContext();
1612 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1614 TRACE("Another GL context (%p on device context %p) is already current.\n",
1615 current_gl, wglGetCurrentDC());
1616 context->restore_ctx = current_gl;
1617 context->restore_dc = wglGetCurrentDC();
1618 context->needs_set = 1;
1620 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1621 && context->pixel_format != context->gl_info->gl_ops.wgl.p_wglGetPixelFormat(context->hdc))
1622 context->needs_set = 1;
1626 void context_invalidate_compute_state(struct wined3d_context *context, DWORD state_id)
1628 DWORD representative = context->state_table[state_id].representative - STATE_COMPUTE_OFFSET;
1629 unsigned int index, shift;
1631 index = representative / (sizeof(*context->dirty_compute_states) * CHAR_BIT);
1632 shift = representative & (sizeof(*context->dirty_compute_states) * CHAR_BIT - 1);
1633 context->dirty_compute_states[index] |= (1u << shift);
1636 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1638 DWORD rep = context->state_table[state].representative;
1639 DWORD idx;
1640 BYTE shift;
1642 if (isStateDirty(context, rep)) return;
1644 context->dirtyArray[context->numDirtyEntries++] = rep;
1645 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1646 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1647 context->isStateDirty[idx] |= (1u << shift);
1650 /* This function takes care of wined3d pixel format selection. */
1651 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1652 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1653 BOOL auxBuffers)
1655 unsigned int cfg_count = device->adapter->cfg_count;
1656 unsigned int current_value;
1657 PIXELFORMATDESCRIPTOR pfd;
1658 int iPixelFormat = 0;
1659 unsigned int i;
1661 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x.\n",
1662 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1663 auxBuffers);
1665 current_value = 0;
1666 for (i = 0; i < cfg_count; ++i)
1668 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1669 unsigned int value;
1671 /* For now only accept RGBA formats. Perhaps some day we will
1672 * allow floating point formats for pbuffers. */
1673 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1674 continue;
1675 /* In window mode we need a window drawable format and double buffering. */
1676 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1677 continue;
1678 if (cfg->redSize < color_format->red_size)
1679 continue;
1680 if (cfg->greenSize < color_format->green_size)
1681 continue;
1682 if (cfg->blueSize < color_format->blue_size)
1683 continue;
1684 if (cfg->alphaSize < color_format->alpha_size)
1685 continue;
1686 if (cfg->depthSize < ds_format->depth_size)
1687 continue;
1688 if (ds_format->stencil_size && cfg->stencilSize != ds_format->stencil_size)
1689 continue;
1690 /* Check multisampling support. */
1691 if (cfg->numSamples)
1692 continue;
1694 value = 1;
1695 /* We try to locate a format which matches our requirements exactly. In case of
1696 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1697 if (cfg->depthSize == ds_format->depth_size)
1698 value += 1;
1699 if (cfg->stencilSize == ds_format->stencil_size)
1700 value += 2;
1701 if (cfg->alphaSize == color_format->alpha_size)
1702 value += 4;
1703 /* We like to have aux buffers in backbuffer mode */
1704 if (auxBuffers && cfg->auxBuffers)
1705 value += 8;
1706 if (cfg->redSize == color_format->red_size
1707 && cfg->greenSize == color_format->green_size
1708 && cfg->blueSize == color_format->blue_size)
1709 value += 16;
1711 if (value > current_value)
1713 iPixelFormat = cfg->iPixelFormat;
1714 current_value = value;
1718 if (!iPixelFormat)
1720 ERR("Trying to locate a compatible pixel format because an exact match failed.\n");
1722 memset(&pfd, 0, sizeof(pfd));
1723 pfd.nSize = sizeof(pfd);
1724 pfd.nVersion = 1;
1725 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1726 pfd.iPixelType = PFD_TYPE_RGBA;
1727 pfd.cAlphaBits = color_format->alpha_size;
1728 pfd.cColorBits = color_format->red_size + color_format->green_size
1729 + color_format->blue_size + color_format->alpha_size;
1730 pfd.cDepthBits = ds_format->depth_size;
1731 pfd.cStencilBits = ds_format->stencil_size;
1732 pfd.iLayerType = PFD_MAIN_PLANE;
1734 if (!(iPixelFormat = ChoosePixelFormat(hdc, &pfd)))
1736 /* Something is very wrong as ChoosePixelFormat() barely fails. */
1737 ERR("Can't find a suitable pixel format.\n");
1738 return 0;
1742 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s.\n",
1743 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1744 return iPixelFormat;
1747 /* Context activation is done by the caller. */
1748 void context_bind_dummy_textures(const struct wined3d_context *context)
1750 const struct wined3d_dummy_textures *textures = &wined3d_device_gl(context->device)->dummy_textures;
1751 const struct wined3d_gl_info *gl_info = context->gl_info;
1752 unsigned int i;
1754 for (i = 0; i < gl_info->limits.combined_samplers; ++i)
1756 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1758 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_1D, textures->tex_1d);
1759 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, textures->tex_2d);
1761 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1762 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, textures->tex_rect);
1764 if (gl_info->supported[EXT_TEXTURE3D])
1765 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, textures->tex_3d);
1767 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1768 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, textures->tex_cube);
1770 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP_ARRAY])
1771 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, textures->tex_cube_array);
1773 if (gl_info->supported[EXT_TEXTURE_ARRAY])
1775 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_1D_ARRAY, textures->tex_1d_array);
1776 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, textures->tex_2d_array);
1779 if (gl_info->supported[ARB_TEXTURE_BUFFER_OBJECT])
1780 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_BUFFER, textures->tex_buffer);
1782 if (gl_info->supported[ARB_TEXTURE_MULTISAMPLE])
1784 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, textures->tex_2d_ms);
1785 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_MULTISAMPLE_ARRAY, textures->tex_2d_ms_array);
1789 checkGLcall("bind dummy textures");
1792 void wined3d_check_gl_call(const struct wined3d_gl_info *gl_info,
1793 const char *file, unsigned int line, const char *name)
1795 GLint err;
1797 if (gl_info->supported[ARB_DEBUG_OUTPUT] || (err = gl_info->gl_ops.gl.p_glGetError()) == GL_NO_ERROR)
1799 TRACE("%s call ok %s / %u.\n", name, file, line);
1800 return;
1805 ERR(">>>>>>> %s (%#x) from %s @ %s / %u.\n",
1806 debug_glerror(err), err, name, file,line);
1807 err = gl_info->gl_ops.gl.p_glGetError();
1808 } while (err != GL_NO_ERROR);
1811 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1813 return gl_info->supported[ARB_DEBUG_OUTPUT]
1814 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1817 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1818 GLenum severity, GLsizei length, const char *message, void *ctx)
1820 switch (type)
1822 case GL_DEBUG_TYPE_ERROR_ARB:
1823 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1824 break;
1826 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1827 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1828 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1829 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1830 break;
1832 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1833 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1834 break;
1836 default:
1837 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1838 break;
1842 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1844 HGLRC ctx;
1845 unsigned int ctx_attrib_idx = 0;
1846 GLint ctx_attribs[7], ctx_flags = 0;
1848 if (context_debug_output_enabled(gl_info))
1849 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1850 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1851 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1852 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1853 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1854 if (ctx_flags)
1856 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1857 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1859 ctx_attribs[ctx_attrib_idx] = 0;
1861 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1863 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1865 if (ctx_flags)
1867 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1868 ctx_attribs[ctx_attrib_idx - 1] = ctx_flags;
1870 else
1872 ctx_flags = WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1873 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1874 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1875 ctx_attribs[ctx_attrib_idx] = 0;
1877 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1878 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1879 GetLastError());
1882 return ctx;
1885 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1886 struct wined3d_texture *target, const struct wined3d_format *ds_format)
1888 struct wined3d_device *device = swapchain->device;
1889 struct wined3d_context *context;
1890 DWORD state;
1892 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1894 wined3d_from_cs(device->cs);
1896 if (!(context = heap_alloc_zero(sizeof(*context))))
1897 return NULL;
1899 context->free_timestamp_query_size = 4;
1900 if (!(context->free_timestamp_queries = heap_calloc(context->free_timestamp_query_size,
1901 sizeof(*context->free_timestamp_queries))))
1902 goto out;
1903 list_init(&context->timestamp_queries);
1905 context->free_occlusion_query_size = 4;
1906 if (!(context->free_occlusion_queries = heap_calloc(context->free_occlusion_query_size,
1907 sizeof(*context->free_occlusion_queries))))
1908 goto out;
1909 list_init(&context->occlusion_queries);
1911 context->free_fence_size = 4;
1912 if (!(context->free_fences = heap_calloc(context->free_fence_size, sizeof(*context->free_fences))))
1913 goto out;
1914 list_init(&context->fences);
1916 list_init(&context->so_statistics_queries);
1918 list_init(&context->pipeline_statistics_queries);
1920 list_init(&context->fbo_list);
1921 list_init(&context->fbo_destroy_list);
1923 if (!device->shader_backend->shader_allocate_context_data(context))
1925 ERR("Failed to allocate shader backend context data.\n");
1926 goto out;
1928 if (!device->adapter->fragment_pipe->allocate_context_data(context))
1930 ERR("Failed to allocate fragment pipeline context data.\n");
1931 goto out;
1934 if (!(context->hdc = GetDCEx(swapchain->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1936 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1938 if ((context->hdc = swapchain_get_backup_dc(swapchain)))
1939 context->hdc_is_private = TRUE;
1940 else
1942 ERR("Failed to retrieve a device context.\n");
1943 goto out;
1947 if (!device_context_add(device, context))
1949 ERR("Failed to add the newly created context to the context list\n");
1950 goto out;
1953 context->win_handle = swapchain->win_handle;
1954 context->gl_info = &device->adapter->gl_info;
1955 context->d3d_info = &device->adapter->d3d_info;
1956 context->state_table = device->StateTable;
1958 /* Mark all states dirty to force a proper initialization of the states on
1959 * the first use of the context. Compute states do not need initialization. */
1960 for (state = 0; state <= STATE_HIGHEST; ++state)
1962 if (context->state_table[state].representative && !STATE_IS_COMPUTE(state))
1963 context_invalidate_state(context, state);
1966 context->device = device;
1967 context->swapchain = swapchain;
1968 context->current_rt.texture = target;
1969 context->current_rt.sub_resource_idx = 0;
1970 context->tid = GetCurrentThreadId();
1972 if (!(device->adapter->adapter_ops->adapter_create_context(context, target, ds_format)))
1974 device_context_remove(device, context);
1975 goto out;
1978 device->shader_backend->shader_init_context_state(context);
1979 context->shader_update_mask = (1u << WINED3D_SHADER_TYPE_PIXEL)
1980 | (1u << WINED3D_SHADER_TYPE_VERTEX)
1981 | (1u << WINED3D_SHADER_TYPE_GEOMETRY)
1982 | (1u << WINED3D_SHADER_TYPE_HULL)
1983 | (1u << WINED3D_SHADER_TYPE_DOMAIN)
1984 | (1u << WINED3D_SHADER_TYPE_COMPUTE);
1986 TRACE("Created context %p.\n", context);
1988 return context;
1990 out:
1991 if (context->hdc)
1992 wined3d_release_dc(swapchain->win_handle, context->hdc);
1993 device->shader_backend->shader_free_context_data(context);
1994 device->adapter->fragment_pipe->free_context_data(context);
1995 heap_free(context->free_fences);
1996 heap_free(context->free_occlusion_queries);
1997 heap_free(context->free_timestamp_queries);
1998 heap_free(context);
1999 return NULL;
2002 BOOL wined3d_adapter_gl_create_context(struct wined3d_context *context,
2003 struct wined3d_texture *target, const struct wined3d_format *ds_format)
2005 struct wined3d_device *device = context->device;
2006 const struct wined3d_format *color_format;
2007 const struct wined3d_d3d_info *d3d_info;
2008 const struct wined3d_gl_info *gl_info;
2009 unsigned int target_bind_flags;
2010 BOOL aux_buffers = FALSE;
2011 HGLRC ctx, share_ctx;
2012 unsigned int i;
2014 gl_info = context->gl_info;
2015 d3d_info = context->d3d_info;
2017 for (i = 0; i < ARRAY_SIZE(context->tex_unit_map); ++i)
2018 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2019 for (i = 0; i < ARRAY_SIZE(context->rev_tex_unit_map); ++i)
2020 context->rev_tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2021 if (gl_info->limits.graphics_samplers >= MAX_COMBINED_SAMPLERS)
2023 /* Initialize the texture unit mapping to a 1:1 mapping. */
2024 unsigned int base, count;
2026 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, WINED3D_SHADER_TYPE_PIXEL, &base, &count);
2027 if (base + MAX_FRAGMENT_SAMPLERS > ARRAY_SIZE(context->rev_tex_unit_map))
2029 ERR("Unexpected texture unit base index %u.\n", base);
2030 return FALSE;
2032 for (i = 0; i < min(count, MAX_FRAGMENT_SAMPLERS); ++i)
2034 context->tex_unit_map[i] = base + i;
2035 context->rev_tex_unit_map[base + i] = i;
2038 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, WINED3D_SHADER_TYPE_VERTEX, &base, &count);
2039 if (base + MAX_VERTEX_SAMPLERS > ARRAY_SIZE(context->rev_tex_unit_map))
2041 ERR("Unexpected texture unit base index %u.\n", base);
2042 return FALSE;
2044 for (i = 0; i < min(count, MAX_VERTEX_SAMPLERS); ++i)
2046 context->tex_unit_map[MAX_FRAGMENT_SAMPLERS + i] = base + i;
2047 context->rev_tex_unit_map[base + i] = MAX_FRAGMENT_SAMPLERS + i;
2051 if (!(context->texture_type = heap_calloc(gl_info->limits.combined_samplers,
2052 sizeof(*context->texture_type))))
2053 return FALSE;
2055 color_format = target->resource.format;
2056 target_bind_flags = target->resource.bind_flags;
2058 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
2059 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
2060 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
2062 aux_buffers = TRUE;
2064 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
2065 color_format = wined3d_get_format(device->adapter, WINED3DFMT_B4G4R4A4_UNORM, target_bind_flags);
2066 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
2067 color_format = wined3d_get_format(device->adapter, WINED3DFMT_B8G8R8A8_UNORM, target_bind_flags);
2070 /* DirectDraw supports 8bit paletted render targets and these are used by
2071 * old games like StarCraft and C&C. Most modern hardware doesn't support
2072 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
2073 * conversion (ab)uses the alpha component for storing the palette index.
2074 * For this reason we require a format with 8bit alpha, so request
2075 * A8R8G8B8. */
2076 if (color_format->id == WINED3DFMT_P8_UINT)
2077 color_format = wined3d_get_format(device->adapter, WINED3DFMT_B8G8R8A8_UNORM, target_bind_flags);
2079 /* When using FBOs for off-screen rendering, we only use the drawable for
2080 * presentation blits, and don't do any rendering to it. That means we
2081 * don't need depth or stencil buffers, and can mostly ignore the render
2082 * target format. This wouldn't necessarily be quite correct for 10bpc
2083 * display modes, but we don't currently support those.
2084 * Using the same format regardless of the color/depth/stencil targets
2085 * makes it much less likely that different wined3d instances will set
2086 * conflicting pixel formats. */
2087 if (wined3d_settings.offscreen_rendering_mode != ORM_BACKBUFFER)
2089 color_format = wined3d_get_format(device->adapter, WINED3DFMT_B8G8R8A8_UNORM, target_bind_flags);
2090 ds_format = wined3d_get_format(device->adapter, WINED3DFMT_UNKNOWN, WINED3D_BIND_DEPTH_STENCIL);
2093 /* Try to find a pixel format which matches our requirements. */
2094 if (!(context->pixel_format = context_choose_pixel_format(device,
2095 context->hdc, color_format, ds_format, aux_buffers)))
2096 return FALSE;
2098 context_enter(context);
2100 if (!context_set_pixel_format(context))
2102 ERR("Failed to set pixel format %d on device context %p.\n", context->pixel_format, context->hdc);
2103 context_release(context);
2104 heap_free(context->texture_type);
2105 return FALSE;
2108 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
2109 if (gl_info->p_wglCreateContextAttribsARB)
2111 if (!(ctx = context_create_wgl_attribs(gl_info, context->hdc, share_ctx)))
2113 context_release(context);
2114 heap_free(context->texture_type);
2115 return FALSE;
2118 else
2120 if (!(ctx = wglCreateContext(context->hdc)))
2122 ERR("Failed to create a WGL context.\n");
2123 context_release(context);
2124 heap_free(context->texture_type);
2125 return FALSE;
2128 if (share_ctx && !wglShareLists(share_ctx, ctx))
2130 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
2131 context_release(context);
2132 if (!wglDeleteContext(ctx))
2133 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
2134 heap_free(context->texture_type);
2135 return FALSE;
2139 context->render_offscreen = wined3d_resource_is_offscreen(&target->resource);
2140 context->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
2141 context->valid = 1;
2143 context->glCtx = ctx;
2144 context->hdc_has_format = TRUE;
2145 context->needs_set = 1;
2147 /* Set up the context defaults */
2148 if (!context_set_current(context))
2150 ERR("Cannot activate context to set up defaults.\n");
2151 context_release(context);
2152 if (!wglDeleteContext(ctx))
2153 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
2154 heap_free(context->texture_type);
2155 return FALSE;
2158 if (context_debug_output_enabled(gl_info))
2160 GL_EXTCALL(glDebugMessageCallback(wined3d_debug_callback, context));
2161 if (TRACE_ON(d3d_synchronous))
2162 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
2163 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
2164 if (ERR_ON(d3d))
2166 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR,
2167 GL_DONT_CARE, 0, NULL, GL_TRUE));
2169 if (FIXME_ON(d3d))
2171 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
2172 GL_DONT_CARE, 0, NULL, GL_TRUE));
2173 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
2174 GL_DONT_CARE, 0, NULL, GL_TRUE));
2175 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY,
2176 GL_DONT_CARE, 0, NULL, GL_TRUE));
2178 if (WARN_ON(d3d_perf))
2180 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE,
2181 GL_DONT_CARE, 0, NULL, GL_TRUE));
2185 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
2186 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &context->aux_buffers);
2188 TRACE("Setting up the screen\n");
2190 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
2192 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
2193 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
2195 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
2196 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
2198 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
2199 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
2201 else
2203 GLuint vao;
2205 GL_EXTCALL(glGenVertexArrays(1, &vao));
2206 GL_EXTCALL(glBindVertexArray(vao));
2207 checkGLcall("creating VAO");
2210 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
2211 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
2212 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
2213 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, 1);");
2215 if (gl_info->supported[NV_TEXTURE_SHADER2])
2217 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
2218 * the previous texture where to source the offset from is always unit - 1.
2220 for (i = 1; i < gl_info->limits.textures; ++i)
2222 context_active_texture(context, gl_info, i);
2223 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
2224 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + i - 1);
2225 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
2228 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
2230 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
2231 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
2232 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
2233 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
2234 * is ever assigned.
2236 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
2237 * program and the dummy program is destroyed when the context is destroyed.
2239 static const char dummy_program[] =
2240 "!!ARBfp1.0\n"
2241 "MOV result.color, fragment.color.primary;\n"
2242 "END\n";
2243 GL_EXTCALL(glGenProgramsARB(1, &context->dummy_arbfp_prog));
2244 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, context->dummy_arbfp_prog));
2245 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB,
2246 GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
2249 if (gl_info->supported[ARB_POINT_SPRITE])
2251 for (i = 0; i < gl_info->limits.textures; ++i)
2253 context_active_texture(context, gl_info, i);
2254 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
2255 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
2259 if (gl_info->supported[ARB_PROVOKING_VERTEX])
2261 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
2263 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
2265 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
2267 if (!(d3d_info->wined3d_creation_flags & WINED3D_NO_PRIMITIVE_RESTART))
2269 if (gl_info->supported[ARB_ES3_COMPATIBILITY])
2271 gl_info->gl_ops.gl.p_glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
2272 checkGLcall("enable GL_PRIMITIVE_RESTART_FIXED_INDEX");
2274 else
2276 FIXME("OpenGL implementation does not support GL_PRIMITIVE_RESTART_FIXED_INDEX.\n");
2279 if (!(d3d_info->wined3d_creation_flags & WINED3D_LEGACY_CUBEMAP_FILTERING)
2280 && gl_info->supported[ARB_SEAMLESS_CUBE_MAP])
2282 gl_info->gl_ops.gl.p_glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
2283 checkGLcall("enable seamless cube map filtering");
2285 if (gl_info->supported[ARB_CLIP_CONTROL])
2286 GL_EXTCALL(glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT));
2288 /* If this happens to be the first context for the device, dummy textures
2289 * are not created yet. In that case, they will be created (and bound) by
2290 * create_dummy_textures right after this context is initialized. */
2291 if (wined3d_device_gl(device)->dummy_textures.tex_2d)
2292 context_bind_dummy_textures(context);
2294 /* Initialise all rectangles to avoid resetting unused ones later. */
2295 gl_info->gl_ops.gl.p_glScissor(0, 0, 0, 0);
2296 checkGLcall("glScissor");
2298 return TRUE;
2301 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
2303 BOOL destroy;
2305 TRACE("Destroying ctx %p\n", context);
2307 wined3d_from_cs(device->cs);
2309 /* We delay destroying a context when it is active. The context_release()
2310 * function invokes context_destroy() again while leaving the last level. */
2311 if (context->level)
2313 TRACE("Delaying destruction of context %p.\n", context);
2314 context->destroy_delayed = 1;
2315 /* FIXME: Get rid of a pointer to swapchain from wined3d_context. */
2316 context->swapchain = NULL;
2317 return;
2320 if (context->tid == GetCurrentThreadId() || !context->current)
2322 context_destroy_gl_resources(context);
2323 TlsSetValue(wined3d_context_tls_idx, NULL);
2324 destroy = TRUE;
2326 else
2328 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
2329 in wined3d_adapter may go away in the meantime */
2330 struct wined3d_gl_info *gl_info = heap_alloc(sizeof(*gl_info));
2331 *gl_info = *context->gl_info;
2332 context->gl_info = gl_info;
2333 context->destroyed = 1;
2334 destroy = FALSE;
2337 device->shader_backend->shader_free_context_data(context);
2338 device->adapter->fragment_pipe->free_context_data(context);
2339 heap_free(context->texture_type);
2340 device_context_remove(device, context);
2341 if (destroy)
2342 heap_free(context);
2345 const DWORD *context_get_tex_unit_mapping(const struct wined3d_context *context,
2346 const struct wined3d_shader_version *shader_version, unsigned int *base, unsigned int *count)
2348 const struct wined3d_gl_info *gl_info = context->gl_info;
2350 if (!shader_version)
2352 *base = 0;
2353 *count = MAX_TEXTURES;
2354 return context->tex_unit_map;
2357 if (shader_version->major >= 4)
2359 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, shader_version->type, base, count);
2360 return NULL;
2363 switch (shader_version->type)
2365 case WINED3D_SHADER_TYPE_PIXEL:
2366 *base = 0;
2367 *count = MAX_FRAGMENT_SAMPLERS;
2368 break;
2369 case WINED3D_SHADER_TYPE_VERTEX:
2370 *base = MAX_FRAGMENT_SAMPLERS;
2371 *count = MAX_VERTEX_SAMPLERS;
2372 break;
2373 default:
2374 ERR("Unhandled shader type %#x.\n", shader_version->type);
2375 *base = 0;
2376 *count = 0;
2379 return context->tex_unit_map;
2382 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
2384 const struct wined3d_texture *rt = context->current_rt.texture;
2385 unsigned int level;
2387 if (rt->swapchain)
2389 RECT window_size;
2391 GetClientRect(context->win_handle, &window_size);
2392 size->cx = window_size.right - window_size.left;
2393 size->cy = window_size.bottom - window_size.top;
2395 return;
2398 level = context->current_rt.sub_resource_idx % rt->level_count;
2399 size->cx = wined3d_texture_get_level_width(rt, level);
2400 size->cy = wined3d_texture_get_level_height(rt, level);
2403 void context_enable_clip_distances(struct wined3d_context *context, unsigned int enable_mask)
2405 const struct wined3d_gl_info *gl_info = context->gl_info;
2406 unsigned int clip_distance_count = gl_info->limits.user_clip_distances;
2407 unsigned int i, disable_mask, current_mask;
2409 disable_mask = ~enable_mask;
2410 enable_mask &= (1u << clip_distance_count) - 1;
2411 disable_mask &= (1u << clip_distance_count) - 1;
2412 current_mask = context->clip_distance_mask;
2413 context->clip_distance_mask = enable_mask;
2415 enable_mask &= ~current_mask;
2416 while (enable_mask)
2418 i = wined3d_bit_scan(&enable_mask);
2419 gl_info->gl_ops.gl.p_glEnable(GL_CLIP_DISTANCE0 + i);
2421 disable_mask &= current_mask;
2422 while (disable_mask)
2424 i = wined3d_bit_scan(&disable_mask);
2425 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_DISTANCE0 + i);
2427 checkGLcall("toggle clip distances");
2430 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2432 return rt_mask & (1u << 31);
2435 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2437 return rt_mask & ~(1u << 31);
2440 /* Context activation is done by the caller. */
2441 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2443 const struct wined3d_gl_info *gl_info = context->gl_info;
2444 GLenum draw_buffers[MAX_RENDER_TARGET_VIEWS];
2446 if (!rt_mask)
2448 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2450 else if (is_rt_mask_onscreen(rt_mask))
2452 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2454 else
2456 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2458 unsigned int i = 0;
2460 while (rt_mask)
2462 if (rt_mask & 1)
2463 draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2464 else
2465 draw_buffers[i] = GL_NONE;
2467 rt_mask >>= 1;
2468 ++i;
2471 if (gl_info->supported[ARB_DRAW_BUFFERS])
2473 GL_EXTCALL(glDrawBuffers(i, draw_buffers));
2475 else
2477 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffers[0]);
2480 else
2482 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2486 checkGLcall("apply draw buffers");
2489 /* Context activation is done by the caller. */
2490 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2492 const struct wined3d_gl_info *gl_info = context->gl_info;
2493 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2494 DWORD new_mask = context_generate_rt_mask(buffer);
2496 if (new_mask == *current_mask)
2497 return;
2499 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2500 checkGLcall("glDrawBuffer()");
2502 *current_mask = new_mask;
2505 /* Context activation is done by the caller. */
2506 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2508 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2509 checkGLcall("glActiveTexture");
2510 context->active_texture = unit;
2513 void context_bind_bo(struct wined3d_context *context, GLenum binding, GLuint name)
2515 const struct wined3d_gl_info *gl_info = context->gl_info;
2517 if (binding == GL_ELEMENT_ARRAY_BUFFER)
2518 context_invalidate_state(context, STATE_INDEXBUFFER);
2520 GL_EXTCALL(glBindBuffer(binding, name));
2523 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2525 const struct wined3d_dummy_textures *textures = &wined3d_device_gl(context->device)->dummy_textures;
2526 const struct wined3d_gl_info *gl_info = context->gl_info;
2527 DWORD unit = context->active_texture;
2528 DWORD old_texture_type = context->texture_type[unit];
2530 if (name)
2532 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2534 else
2536 target = GL_NONE;
2539 if (old_texture_type != target)
2541 switch (old_texture_type)
2543 case GL_NONE:
2544 /* nothing to do */
2545 break;
2546 case GL_TEXTURE_1D:
2547 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_1D, textures->tex_1d);
2548 break;
2549 case GL_TEXTURE_1D_ARRAY:
2550 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_1D_ARRAY, textures->tex_1d_array);
2551 break;
2552 case GL_TEXTURE_2D:
2553 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, textures->tex_2d);
2554 break;
2555 case GL_TEXTURE_2D_ARRAY:
2556 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, textures->tex_2d_array);
2557 break;
2558 case GL_TEXTURE_RECTANGLE_ARB:
2559 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, textures->tex_rect);
2560 break;
2561 case GL_TEXTURE_CUBE_MAP:
2562 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, textures->tex_cube);
2563 break;
2564 case GL_TEXTURE_CUBE_MAP_ARRAY:
2565 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, textures->tex_cube_array);
2566 break;
2567 case GL_TEXTURE_3D:
2568 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, textures->tex_3d);
2569 break;
2570 case GL_TEXTURE_BUFFER:
2571 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_BUFFER, textures->tex_buffer);
2572 break;
2573 case GL_TEXTURE_2D_MULTISAMPLE:
2574 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, textures->tex_2d_ms);
2575 break;
2576 case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
2577 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_MULTISAMPLE_ARRAY, textures->tex_2d_ms_array);
2578 break;
2579 default:
2580 ERR("Unexpected texture target %#x.\n", old_texture_type);
2583 context->texture_type[unit] = target;
2586 checkGLcall("bind texture");
2589 void *context_map_bo_address(struct wined3d_context *context,
2590 const struct wined3d_bo_address *data, size_t size, GLenum binding, DWORD flags)
2592 const struct wined3d_gl_info *gl_info;
2593 BYTE *memory;
2595 if (!data->buffer_object)
2596 return data->addr;
2598 gl_info = context->gl_info;
2599 context_bind_bo(context, binding, data->buffer_object);
2601 if (gl_info->supported[ARB_MAP_BUFFER_RANGE])
2603 GLbitfield map_flags = wined3d_resource_gl_map_flags(flags) & ~GL_MAP_FLUSH_EXPLICIT_BIT;
2604 memory = GL_EXTCALL(glMapBufferRange(binding, (INT_PTR)data->addr, size, map_flags));
2606 else
2608 memory = GL_EXTCALL(glMapBuffer(binding, wined3d_resource_gl_legacy_map_flags(flags)));
2609 memory += (INT_PTR)data->addr;
2612 context_bind_bo(context, binding, 0);
2613 checkGLcall("Map buffer object");
2615 return memory;
2618 void context_unmap_bo_address(struct wined3d_context *context,
2619 const struct wined3d_bo_address *data, GLenum binding)
2621 const struct wined3d_gl_info *gl_info;
2623 if (!data->buffer_object)
2624 return;
2626 gl_info = context->gl_info;
2627 context_bind_bo(context, binding, data->buffer_object);
2628 GL_EXTCALL(glUnmapBuffer(binding));
2629 context_bind_bo(context, binding, 0);
2630 checkGLcall("Unmap buffer object");
2633 void context_copy_bo_address(struct wined3d_context *context,
2634 const struct wined3d_bo_address *dst, GLenum dst_binding,
2635 const struct wined3d_bo_address *src, GLenum src_binding, size_t size)
2637 const struct wined3d_gl_info *gl_info;
2638 BYTE *dst_ptr, *src_ptr;
2640 gl_info = context->gl_info;
2642 if (dst->buffer_object && src->buffer_object)
2644 if (gl_info->supported[ARB_COPY_BUFFER])
2646 GL_EXTCALL(glBindBuffer(GL_COPY_READ_BUFFER, src->buffer_object));
2647 GL_EXTCALL(glBindBuffer(GL_COPY_WRITE_BUFFER, dst->buffer_object));
2648 GL_EXTCALL(glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER,
2649 (GLintptr)src->addr, (GLintptr)dst->addr, size));
2650 checkGLcall("direct buffer copy");
2652 else
2654 src_ptr = context_map_bo_address(context, src, size, src_binding, WINED3D_MAP_READ);
2655 dst_ptr = context_map_bo_address(context, dst, size, dst_binding, WINED3D_MAP_WRITE);
2657 memcpy(dst_ptr, src_ptr, size);
2659 context_unmap_bo_address(context, dst, dst_binding);
2660 context_unmap_bo_address(context, src, src_binding);
2663 else if (!dst->buffer_object && src->buffer_object)
2665 context_bind_bo(context, src_binding, src->buffer_object);
2666 GL_EXTCALL(glGetBufferSubData(src_binding, (GLintptr)src->addr, size, dst->addr));
2667 checkGLcall("buffer download");
2669 else if (dst->buffer_object && !src->buffer_object)
2671 context_bind_bo(context, dst_binding, dst->buffer_object);
2672 GL_EXTCALL(glBufferSubData(dst_binding, (GLintptr)dst->addr, size, src->addr));
2673 checkGLcall("buffer upload");
2675 else
2677 memcpy(dst->addr, src->addr, size);
2681 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2683 if (context->render_offscreen == offscreen)
2684 return;
2686 context_invalidate_state(context, STATE_VIEWPORT);
2687 context_invalidate_state(context, STATE_SCISSORRECT);
2688 if (!context->gl_info->supported[ARB_CLIP_CONTROL])
2690 context_invalidate_state(context, STATE_RASTERIZER);
2691 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2692 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2694 context_invalidate_state(context, STATE_SHADER(WINED3D_SHADER_TYPE_DOMAIN));
2695 if (context->gl_info->supported[ARB_FRAGMENT_COORD_CONVENTIONS])
2696 context_invalidate_state(context, STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL));
2697 context->render_offscreen = offscreen;
2700 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2701 const struct wined3d_format *required)
2703 if (existing == required)
2704 return TRUE;
2705 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2706 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2707 return FALSE;
2708 if (existing->depth_size < required->depth_size)
2709 return FALSE;
2710 /* If stencil bits are used the exact amount is required - otherwise
2711 * wrapping won't work correctly. */
2712 if (required->stencil_size && required->stencil_size != existing->stencil_size)
2713 return FALSE;
2714 return TRUE;
2717 /* Context activation is done by the caller. */
2718 static void context_validate_onscreen_formats(struct wined3d_context *context,
2719 const struct wined3d_rendertarget_view *depth_stencil)
2721 /* Onscreen surfaces are always in a swapchain */
2722 struct wined3d_swapchain *swapchain = context->current_rt.texture->swapchain;
2724 if (context->render_offscreen || !depth_stencil) return;
2725 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2727 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2728 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2729 * format. */
2730 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2732 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2733 if (!(wined3d_texture_load_location(context->current_rt.texture, context->current_rt.sub_resource_idx,
2734 context, WINED3D_LOCATION_TEXTURE_RGB)))
2735 ERR("Failed to load location.\n");
2736 swapchain->render_to_fbo = TRUE;
2737 swapchain_update_draw_bindings(swapchain);
2738 context_set_render_offscreen(context, TRUE);
2741 GLenum context_get_offscreen_gl_buffer(const struct wined3d_context *context)
2743 switch (wined3d_settings.offscreen_rendering_mode)
2745 case ORM_FBO:
2746 return GL_COLOR_ATTACHMENT0;
2748 case ORM_BACKBUFFER:
2749 return context->aux_buffers > 0 ? GL_AUX0 : GL_BACK;
2751 default:
2752 FIXME("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
2753 return GL_BACK;
2757 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_context *context, struct wined3d_resource *rt)
2759 if (!rt || rt->format->id == WINED3DFMT_NULL)
2760 return 0;
2761 else if (rt->type != WINED3D_RTYPE_BUFFER && texture_from_resource(rt)->swapchain)
2762 return context_generate_rt_mask_from_resource(rt);
2763 else
2764 return context_generate_rt_mask(context_get_offscreen_gl_buffer(context));
2767 /* Context activation is done by the caller. */
2768 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2770 const struct wined3d_gl_info *gl_info = context->gl_info;
2771 struct wined3d_texture *rt = context->current_rt.texture;
2772 DWORD rt_mask, *cur_mask;
2773 unsigned int sampler;
2774 SIZE rt_size;
2776 TRACE("Setting up context %p for blitting.\n", context);
2778 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2780 if (context->render_offscreen)
2782 wined3d_texture_load(rt, context, FALSE);
2784 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, &rt->resource,
2785 context->current_rt.sub_resource_idx, NULL, 0, rt->resource.draw_binding);
2786 if (rt->resource.format->id != WINED3DFMT_NULL)
2787 rt_mask = 1;
2788 else
2789 rt_mask = 0;
2791 else
2793 context->current_fbo = NULL;
2794 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2795 rt_mask = context_generate_rt_mask_from_resource(&rt->resource);
2798 else
2800 rt_mask = context_generate_rt_mask_no_fbo(context, &rt->resource);
2803 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2805 if (rt_mask != *cur_mask)
2807 context_apply_draw_buffers(context, rt_mask);
2808 *cur_mask = rt_mask;
2811 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2813 context_check_fbo_status(context, GL_FRAMEBUFFER);
2815 context_invalidate_state(context, STATE_FRAMEBUFFER);
2817 context_get_rt_size(context, &rt_size);
2819 if (context->last_was_blit)
2821 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
2823 gl_info->gl_ops.gl.p_glViewport(0, 0, rt_size.cx, rt_size.cy);
2824 context->viewport_count = WINED3D_MAX_VIEWPORTS;
2825 context->blit_w = rt_size.cx;
2826 context->blit_h = rt_size.cy;
2827 /* No need to dirtify here, the states are still dirtified because
2828 * they weren't applied since the last context_apply_blit_state()
2829 * call. */
2831 checkGLcall("blit state application");
2832 TRACE("Context is already set up for blitting, nothing to do.\n");
2833 return;
2835 context->last_was_blit = TRUE;
2837 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
2838 GL_EXTCALL(glBindSampler(0, 0));
2839 context_active_texture(context, gl_info, 0);
2841 sampler = context->rev_tex_unit_map[0];
2842 if (sampler != WINED3D_UNMAPPED_STAGE)
2844 if (sampler < MAX_TEXTURES)
2846 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
2847 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2849 context_invalidate_state(context, STATE_SAMPLER(sampler));
2851 context_invalidate_compute_state(context, STATE_COMPUTE_SHADER_RESOURCE_BINDING);
2852 context_invalidate_state(context, STATE_GRAPHICS_SHADER_RESOURCE_BINDING);
2854 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
2856 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2857 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2859 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2860 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2861 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2862 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2863 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2864 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2865 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2866 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2867 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2868 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2869 if (gl_info->supported[ARB_POINT_SPRITE])
2871 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2872 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2874 if (gl_info->supported[ARB_FRAMEBUFFER_SRGB])
2876 gl_info->gl_ops.gl.p_glDisable(GL_FRAMEBUFFER_SRGB);
2877 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2879 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2880 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2881 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2882 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2883 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2885 context->last_was_rhw = TRUE;
2886 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2888 context_enable_clip_distances(context, 0);
2889 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2891 /* FIXME: Make draw_textured_quad() able to work with a upper left origin. */
2892 if (gl_info->supported[ARB_CLIP_CONTROL])
2893 GL_EXTCALL(glClipControl(GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE));
2894 gl_info->gl_ops.gl.p_glViewport(0, 0, rt_size.cx, rt_size.cy);
2895 context->viewport_count = WINED3D_MAX_VIEWPORTS;
2896 context_invalidate_state(context, STATE_VIEWPORT);
2898 device->shader_backend->shader_disable(device->shader_priv, context);
2900 context->blit_w = rt_size.cx;
2901 context->blit_h = rt_size.cy;
2903 checkGLcall("blit state application");
2906 static void context_apply_blit_projection(const struct wined3d_context *context, unsigned int w, unsigned int h)
2908 const struct wined3d_gl_info *gl_info = context->gl_info;
2909 const GLdouble projection[] =
2911 2.0 / w, 0.0, 0.0, 0.0,
2912 0.0, 2.0 / h, 0.0, 0.0,
2913 0.0, 0.0, 2.0, 0.0,
2914 -1.0, -1.0, -1.0, 1.0,
2917 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
2918 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
2921 /* Setup OpenGL states for fixed-function blitting. */
2922 /* Context activation is done by the caller. */
2923 void context_apply_ffp_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2925 const struct wined3d_gl_info *gl_info = context->gl_info;
2926 unsigned int i, sampler;
2928 if (!gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
2929 ERR("Applying fixed-function state without legacy context support.\n");
2931 if (context->last_was_ffp_blit)
2933 SIZE rt_size;
2935 context_get_rt_size(context, &rt_size);
2936 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
2937 context_apply_blit_projection(context, rt_size.cx, rt_size.cy);
2938 context_apply_blit_state(context, device);
2940 checkGLcall("ffp blit state application");
2941 return;
2943 context->last_was_ffp_blit = TRUE;
2945 context_apply_blit_state(context, device);
2947 /* Disable all textures. The caller can then bind a texture it wants to blit
2948 * from. */
2949 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
2951 context_active_texture(context, gl_info, i);
2953 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2954 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2955 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2956 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2957 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2958 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2960 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2962 sampler = context->rev_tex_unit_map[i];
2963 if (sampler != WINED3D_UNMAPPED_STAGE)
2965 if (sampler < MAX_TEXTURES)
2966 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2967 context_invalidate_state(context, STATE_SAMPLER(sampler));
2971 context_active_texture(context, gl_info, 0);
2973 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2974 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2975 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2976 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2977 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2978 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2980 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2981 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2982 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
2984 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
2985 gl_info->gl_ops.gl.p_glLoadIdentity();
2987 /* Setup transforms. */
2988 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2989 gl_info->gl_ops.gl.p_glLoadIdentity();
2990 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2991 context_apply_blit_projection(context, context->blit_w, context->blit_h);
2992 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2994 /* Other misc states. */
2995 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2996 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2997 glDisableWINE(GL_FOG);
2998 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
3000 if (gl_info->supported[EXT_SECONDARY_COLOR])
3002 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
3003 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
3005 checkGLcall("ffp blit state application");
3008 static BOOL have_framebuffer_attachment(unsigned int rt_count, struct wined3d_rendertarget_view * const *rts,
3009 const struct wined3d_rendertarget_view *ds)
3011 unsigned int i;
3013 if (ds)
3014 return TRUE;
3016 for (i = 0; i < rt_count; ++i)
3018 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
3019 return TRUE;
3022 return FALSE;
3025 /* Context activation is done by the caller. */
3026 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_state *state,
3027 UINT rt_count, const struct wined3d_fb_state *fb)
3029 struct wined3d_rendertarget_view * const *rts = fb->render_targets;
3030 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
3031 const struct wined3d_gl_info *gl_info = context->gl_info;
3032 DWORD rt_mask = 0, *cur_mask;
3033 unsigned int i;
3035 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != state->fb
3036 || rt_count != gl_info->limits.buffers)
3038 if (!have_framebuffer_attachment(rt_count, rts, dsv))
3040 WARN("Invalid render target config, need at least one attachment.\n");
3041 return FALSE;
3044 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3046 struct wined3d_rendertarget_info ds_info = {{0}};
3048 context_validate_onscreen_formats(context, dsv);
3050 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
3052 memset(context->blit_targets, 0, sizeof(context->blit_targets));
3053 for (i = 0; i < rt_count; ++i)
3055 if (rts[i])
3057 struct wined3d_rendertarget_view_gl *rtv_gl = wined3d_rendertarget_view_gl(rts[i]);
3058 context->blit_targets[i].gl_view = rtv_gl->gl_view;
3059 context->blit_targets[i].resource = rtv_gl->v.resource;
3060 context->blit_targets[i].sub_resource_idx = rtv_gl->v.sub_resource_idx;
3061 context->blit_targets[i].layer_count = rtv_gl->v.layer_count;
3063 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
3064 rt_mask |= (1u << i);
3067 if (dsv)
3069 struct wined3d_rendertarget_view_gl *dsv_gl = wined3d_rendertarget_view_gl(dsv);
3070 ds_info.gl_view = dsv_gl->gl_view;
3071 ds_info.resource = dsv_gl->v.resource;
3072 ds_info.sub_resource_idx = dsv_gl->v.sub_resource_idx;
3073 ds_info.layer_count = dsv_gl->v.layer_count;
3076 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets, &ds_info,
3077 rt_count ? rts[0]->resource->draw_binding : 0,
3078 dsv ? dsv->resource->draw_binding : 0);
3080 else
3082 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, &ds_info,
3083 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
3084 rt_mask = context_generate_rt_mask_from_resource(rts[0]->resource);
3087 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
3088 * next draw. Otherwise we could mark the framebuffer state clean here, once the
3089 * state management allows this */
3090 context_invalidate_state(context, STATE_FRAMEBUFFER);
3092 else
3094 rt_mask = context_generate_rt_mask_no_fbo(context, rt_count ? rts[0]->resource : NULL);
3097 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
3098 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
3100 for (i = 0; i < rt_count; ++i)
3102 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
3103 rt_mask |= (1u << i);
3106 else
3108 rt_mask = context_generate_rt_mask_no_fbo(context, rt_count ? rts[0]->resource : NULL);
3111 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3113 if (rt_mask != *cur_mask)
3115 context_apply_draw_buffers(context, rt_mask);
3116 *cur_mask = rt_mask;
3117 context_invalidate_state(context, STATE_FRAMEBUFFER);
3120 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3122 context_check_fbo_status(context, GL_FRAMEBUFFER);
3125 context->last_was_blit = FALSE;
3126 context->last_was_ffp_blit = FALSE;
3128 /* Blending and clearing should be orthogonal, but tests on the nvidia
3129 * driver show that disabling blending when clearing improves the clearing
3130 * performance incredibly. */
3131 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
3132 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
3133 if (rt_count && gl_info->supported[ARB_FRAMEBUFFER_SRGB])
3135 if (needs_srgb_write(context, state, fb))
3136 gl_info->gl_ops.gl.p_glEnable(GL_FRAMEBUFFER_SRGB);
3137 else
3138 gl_info->gl_ops.gl.p_glDisable(GL_FRAMEBUFFER_SRGB);
3139 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3141 checkGLcall("setting up state for clear");
3143 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3144 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
3145 context_invalidate_state(context, STATE_SCISSORRECT);
3147 return TRUE;
3150 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_state *state)
3152 struct wined3d_rendertarget_view * const *rts = state->fb->render_targets;
3153 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
3154 DWORD rt_mask, mask;
3155 unsigned int i;
3157 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
3158 return context_generate_rt_mask_no_fbo(context, rts[0]->resource);
3159 else if (!context->render_offscreen)
3160 return context_generate_rt_mask_from_resource(rts[0]->resource);
3162 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
3163 rt_mask &= context->d3d_info->valid_rt_mask;
3165 mask = rt_mask;
3166 while (mask)
3168 i = wined3d_bit_scan(&mask);
3169 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
3170 rt_mask &= ~(1u << i);
3173 return rt_mask;
3176 /* Context activation is done by the caller. */
3177 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
3179 DWORD rt_mask = find_draw_buffers_mask(context, state);
3180 const struct wined3d_fb_state *fb = state->fb;
3181 DWORD color_location = 0;
3182 DWORD *cur_mask;
3184 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3186 struct wined3d_rendertarget_info ds_info = {{0}};
3188 if (!context->render_offscreen)
3190 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, &ds_info,
3191 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
3193 else
3195 const struct wined3d_rendertarget_view_gl *view_gl;
3196 unsigned int i;
3198 memset(context->blit_targets, 0, sizeof(context->blit_targets));
3199 for (i = 0; i < context->gl_info->limits.buffers; ++i)
3201 if (!fb->render_targets[i])
3202 continue;
3204 view_gl = wined3d_rendertarget_view_gl(fb->render_targets[i]);
3205 context->blit_targets[i].gl_view = view_gl->gl_view;
3206 context->blit_targets[i].resource = view_gl->v.resource;
3207 context->blit_targets[i].sub_resource_idx = view_gl->v.sub_resource_idx;
3208 context->blit_targets[i].layer_count = view_gl->v.layer_count;
3210 if (!color_location)
3211 color_location = view_gl->v.resource->draw_binding;
3214 if (fb->depth_stencil)
3216 view_gl = wined3d_rendertarget_view_gl(fb->depth_stencil);
3217 ds_info.gl_view = view_gl->gl_view;
3218 ds_info.resource = view_gl->v.resource;
3219 ds_info.sub_resource_idx = view_gl->v.sub_resource_idx;
3220 ds_info.layer_count = view_gl->v.layer_count;
3223 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets, &ds_info,
3224 color_location, fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
3228 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3229 if (rt_mask != *cur_mask)
3231 context_apply_draw_buffers(context, rt_mask);
3232 *cur_mask = rt_mask;
3234 context->constant_update_mask |= WINED3D_SHADER_CONST_PS_Y_CORR;
3237 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
3239 DWORD i = context->rev_tex_unit_map[unit];
3240 DWORD j = context->tex_unit_map[stage];
3242 TRACE("Mapping stage %u to unit %u.\n", stage, unit);
3243 context->tex_unit_map[stage] = unit;
3244 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
3245 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
3247 context->rev_tex_unit_map[unit] = stage;
3248 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
3249 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
3252 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
3254 DWORD i;
3256 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
3257 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
3260 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
3261 const struct wined3d_state *state)
3263 UINT i, start, end;
3265 context->fixed_function_usage_map = 0;
3266 for (i = 0; i < MAX_TEXTURES; ++i)
3268 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
3269 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
3270 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
3271 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
3272 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
3273 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
3274 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
3275 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
3277 /* Not used, and disable higher stages. */
3278 if (color_op == WINED3D_TOP_DISABLE)
3279 break;
3281 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
3282 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
3283 || ((color_arg3 == WINED3DTA_TEXTURE)
3284 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
3285 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
3286 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
3287 || ((alpha_arg3 == WINED3DTA_TEXTURE)
3288 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
3289 context->fixed_function_usage_map |= (1u << i);
3291 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
3292 && i < MAX_TEXTURES - 1)
3293 context->fixed_function_usage_map |= (1u << (i + 1));
3296 if (i < context->lowest_disabled_stage)
3298 start = i;
3299 end = context->lowest_disabled_stage;
3301 else
3303 start = context->lowest_disabled_stage;
3304 end = i;
3307 context->lowest_disabled_stage = i;
3308 for (i = start + 1; i < end; ++i)
3310 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3314 static void context_map_fixed_function_samplers(struct wined3d_context *context,
3315 const struct wined3d_state *state)
3317 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3318 unsigned int i, tex;
3319 WORD ffu_map;
3321 ffu_map = context->fixed_function_usage_map;
3323 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
3324 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
3326 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3328 if (!(ffu_map & 1))
3329 continue;
3331 if (context->tex_unit_map[i] != i)
3333 context_map_stage(context, i, i);
3334 context_invalidate_state(context, STATE_SAMPLER(i));
3335 context_invalidate_texture_stage(context, i);
3338 return;
3341 /* Now work out the mapping */
3342 tex = 0;
3343 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3345 if (!(ffu_map & 1))
3346 continue;
3348 if (context->tex_unit_map[i] != tex)
3350 context_map_stage(context, i, tex);
3351 context_invalidate_state(context, STATE_SAMPLER(i));
3352 context_invalidate_texture_stage(context, i);
3355 ++tex;
3359 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
3361 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3362 const struct wined3d_shader_resource_info *resource_info =
3363 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
3364 unsigned int i;
3366 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3368 if (resource_info[i].type && context->tex_unit_map[i] != i)
3370 context_map_stage(context, i, i);
3371 context_invalidate_state(context, STATE_SAMPLER(i));
3372 if (i < d3d_info->limits.ffp_blend_stages)
3373 context_invalidate_texture_stage(context, i);
3378 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
3379 const struct wined3d_shader_resource_info *ps_resource_info, DWORD unit)
3381 DWORD current_mapping = context->rev_tex_unit_map[unit];
3383 /* Not currently used */
3384 if (current_mapping == WINED3D_UNMAPPED_STAGE)
3385 return TRUE;
3387 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
3389 /* Used by a fragment sampler */
3391 if (!ps_resource_info)
3393 /* No pixel shader, check fixed function */
3394 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1u << current_mapping));
3397 /* Pixel shader, check the shader's sampler map */
3398 return !ps_resource_info[current_mapping].type;
3401 return TRUE;
3404 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
3406 const struct wined3d_shader_resource_info *vs_resource_info =
3407 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
3408 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
3409 const struct wined3d_gl_info *gl_info = context->gl_info;
3410 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.graphics_samplers) - 1;
3411 int i;
3413 /* Note that we only care if a resource is used or not, not the
3414 * resource's specific type. Otherwise we'd need to call
3415 * shader_update_samplers() here for 1.x pixelshaders. */
3416 if (ps)
3417 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
3419 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3421 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
3422 if (vs_resource_info[i].type)
3424 while (start >= 0)
3426 if (context_unit_free_for_vs(context, ps_resource_info, start))
3428 if (context->tex_unit_map[vsampler_idx] != start)
3430 context_map_stage(context, vsampler_idx, start);
3431 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
3434 --start;
3435 break;
3438 --start;
3440 if (context->tex_unit_map[vsampler_idx] == WINED3D_UNMAPPED_STAGE)
3441 WARN("Couldn't find a free texture unit for vertex sampler %u.\n", i);
3446 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
3448 const struct wined3d_gl_info *gl_info = context->gl_info;
3449 BOOL vs = use_vs(state);
3450 BOOL ps = use_ps(state);
3452 if (!ps)
3453 context_update_fixed_function_usage_map(context, state);
3455 /* Try to go for a 1:1 mapping of the samplers when possible. Pixel shaders
3456 * need a 1:1 map at the moment.
3457 * When the mapping of a stage is changed, sampler and ALL texture stage
3458 * states have to be reset. */
3460 if (gl_info->limits.graphics_samplers >= MAX_COMBINED_SAMPLERS)
3461 return;
3463 if (ps)
3464 context_map_psamplers(context, state);
3465 else
3466 context_map_fixed_function_samplers(context, state);
3468 if (vs)
3469 context_map_vsamplers(context, ps, state);
3472 /* Context activation is done by the caller. */
3473 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
3475 DWORD rt_mask, *cur_mask;
3477 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
3479 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3480 rt_mask = find_draw_buffers_mask(context, state);
3481 if (rt_mask != *cur_mask)
3483 context_apply_draw_buffers(context, rt_mask);
3484 *cur_mask = rt_mask;
3488 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
3490 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
3491 *regnum = WINED3D_FFP_POSITION;
3492 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
3493 *regnum = WINED3D_FFP_BLENDWEIGHT;
3494 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
3495 *regnum = WINED3D_FFP_BLENDINDICES;
3496 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
3497 *regnum = WINED3D_FFP_NORMAL;
3498 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
3499 *regnum = WINED3D_FFP_PSIZE;
3500 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
3501 *regnum = WINED3D_FFP_DIFFUSE;
3502 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
3503 *regnum = WINED3D_FFP_SPECULAR;
3504 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
3505 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
3506 else
3508 WARN("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
3509 *regnum = ~0u;
3510 return FALSE;
3513 return TRUE;
3516 /* Context activation is done by the caller. */
3517 void wined3d_stream_info_from_declaration(struct wined3d_stream_info *stream_info,
3518 const struct wined3d_state *state, const struct wined3d_gl_info *gl_info,
3519 const struct wined3d_d3d_info *d3d_info)
3521 /* We need to deal with frequency data! */
3522 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
3523 BOOL generic_attributes = d3d_info->ffp_generic_attributes;
3524 BOOL use_vshader = use_vs(state);
3525 unsigned int i;
3527 stream_info->use_map = 0;
3528 stream_info->swizzle_map = 0;
3529 stream_info->position_transformed = 0;
3531 if (!declaration)
3532 return;
3534 stream_info->position_transformed = declaration->position_transformed;
3536 /* Translate the declaration into strided data. */
3537 for (i = 0; i < declaration->element_count; ++i)
3539 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
3540 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
3541 BOOL stride_used;
3542 unsigned int idx;
3544 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
3545 element, i + 1, declaration->element_count);
3547 if (!stream->buffer)
3548 continue;
3550 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
3552 if (use_vshader)
3554 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
3556 stride_used = FALSE;
3558 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
3560 /* TODO: Assuming vertexdeclarations are usually used with the
3561 * same or a similar shader, it might be worth it to store the
3562 * last used output slot and try that one first. */
3563 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
3564 element->usage, element->usage_idx, &idx);
3566 else
3568 idx = element->output_slot;
3569 stride_used = TRUE;
3572 else
3574 if (!generic_attributes && !element->ffp_valid)
3576 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
3577 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
3578 stride_used = FALSE;
3580 else
3582 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
3586 if (stride_used)
3588 TRACE("Load %s array %u [usage %s, usage_idx %u, "
3589 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
3590 use_vshader ? "shader": "fixed function", idx,
3591 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
3592 element->offset, stream->stride, debug_d3dformat(element->format->id),
3593 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
3595 stream_info->elements[idx].format = element->format;
3596 stream_info->elements[idx].data.buffer_object = 0;
3597 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
3598 stream_info->elements[idx].stride = stream->stride;
3599 stream_info->elements[idx].stream_idx = element->input_slot;
3600 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
3602 stream_info->elements[idx].divisor = 1;
3604 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
3606 stream_info->elements[idx].divisor = element->instance_data_step_rate;
3607 if (!element->instance_data_step_rate)
3608 FIXME("Instance step rate 0 not implemented.\n");
3610 else
3612 stream_info->elements[idx].divisor = 0;
3615 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3616 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
3618 stream_info->swizzle_map |= 1u << idx;
3620 stream_info->use_map |= 1u << idx;
3625 /* Context activation is done by the caller. */
3626 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
3628 struct wined3d_stream_info *stream_info = &context->stream_info;
3629 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3630 const struct wined3d_gl_info *gl_info = context->gl_info;
3631 DWORD prev_all_vbo = stream_info->all_vbo;
3632 unsigned int i;
3633 WORD map;
3635 wined3d_stream_info_from_declaration(stream_info, state, gl_info, d3d_info);
3637 stream_info->all_vbo = 1;
3638 context->buffer_fence_count = 0;
3639 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
3641 struct wined3d_stream_info_element *element;
3642 struct wined3d_bo_address data;
3643 struct wined3d_buffer *buffer;
3645 if (!(map & 1))
3646 continue;
3648 element = &stream_info->elements[i];
3649 buffer = state->streams[element->stream_idx].buffer;
3651 /* We can't use VBOs if the base vertex index is negative. OpenGL
3652 * doesn't accept negative offsets (or rather offsets bigger than the
3653 * VBO, because the pointer is unsigned), so use system memory
3654 * sources. In most sane cases the pointer - offset will still be > 0,
3655 * otherwise it will wrap around to some big value. Hope that with the
3656 * indices the driver wraps it back internally. If not,
3657 * draw_primitive_immediate_mode() is needed, including a vertex buffer
3658 * path. */
3659 if (state->load_base_vertex_index < 0)
3661 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
3662 state->load_base_vertex_index);
3663 element->data.buffer_object = 0;
3664 element->data.addr += (ULONG_PTR)wined3d_buffer_load_sysmem(buffer, context);
3665 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
3666 FIXME("System memory vertex data load offset is negative!\n");
3668 else
3670 wined3d_buffer_load(buffer, context, state);
3671 wined3d_buffer_get_memory(buffer, &data, buffer->locations);
3672 element->data.buffer_object = data.buffer_object;
3673 element->data.addr += (ULONG_PTR)data.addr;
3676 if (!element->data.buffer_object)
3677 stream_info->all_vbo = 0;
3679 if (buffer->fence)
3680 context->buffer_fences[context->buffer_fence_count++] = buffer->fence;
3682 TRACE("Load array %u %s.\n", i, debug_bo_address(&element->data));
3685 if (prev_all_vbo != stream_info->all_vbo)
3686 context_invalidate_state(context, STATE_INDEXBUFFER);
3688 context->use_immediate_mode_draw = FALSE;
3690 if (stream_info->all_vbo)
3691 return;
3693 if (use_vs(state))
3695 if (state->vertex_declaration->have_half_floats && !gl_info->supported[ARB_HALF_FLOAT_VERTEX])
3697 TRACE("Using immediate mode draw with vertex shaders for FLOAT16 conversion.\n");
3698 context->use_immediate_mode_draw = TRUE;
3701 else
3703 WORD slow_mask = -!d3d_info->ffp_generic_attributes & (1u << WINED3D_FFP_PSIZE);
3704 slow_mask |= -(!gl_info->supported[ARB_VERTEX_ARRAY_BGRA] && !d3d_info->ffp_generic_attributes)
3705 & ((1u << WINED3D_FFP_DIFFUSE) | (1u << WINED3D_FFP_SPECULAR) | (1u << WINED3D_FFP_BLENDWEIGHT));
3707 if ((stream_info->position_transformed && !d3d_info->xyzrhw)
3708 || (stream_info->use_map & slow_mask))
3709 context->use_immediate_mode_draw = TRUE;
3713 /* Context activation is done by the caller. */
3714 static void context_preload_texture(struct wined3d_context *context,
3715 const struct wined3d_state *state, unsigned int idx)
3717 struct wined3d_texture *texture;
3719 if (!(texture = state->textures[idx]))
3720 return;
3722 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3725 /* Context activation is done by the caller. */
3726 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3728 unsigned int i;
3730 if (use_vs(state))
3732 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3734 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3735 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3739 if (use_ps(state))
3741 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3743 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3744 context_preload_texture(context, state, i);
3747 else
3749 WORD ffu_map = context->fixed_function_usage_map;
3751 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3753 if (ffu_map & 1)
3754 context_preload_texture(context, state, i);
3759 static void context_load_shader_resources(struct wined3d_context *context, const struct wined3d_state *state,
3760 unsigned int shader_mask)
3762 struct wined3d_shader_sampler_map_entry *entry;
3763 struct wined3d_shader_resource_view *view;
3764 struct wined3d_shader *shader;
3765 unsigned int i, j;
3767 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3769 if (!(shader_mask & (1u << i)))
3770 continue;
3772 if (!(shader = state->shader[i]))
3773 continue;
3775 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3777 if (state->cb[i][j])
3778 wined3d_buffer_load(state->cb[i][j], context, state);
3781 for (j = 0; j < shader->reg_maps.sampler_map.count; ++j)
3783 entry = &shader->reg_maps.sampler_map.entries[j];
3785 if (!(view = state->shader_resource_view[i][entry->resource_idx]))
3786 continue;
3788 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3789 wined3d_buffer_load(buffer_from_resource(view->resource), context, state);
3790 else
3791 wined3d_texture_load(texture_from_resource(view->resource), context, FALSE);
3796 static void context_bind_shader_resources(struct wined3d_context *context,
3797 const struct wined3d_state *state, enum wined3d_shader_type shader_type)
3799 unsigned int bind_idx, shader_sampler_count, base, count, i;
3800 const struct wined3d_device *device = context->device;
3801 struct wined3d_shader_sampler_map_entry *entry;
3802 struct wined3d_shader_resource_view *view;
3803 const struct wined3d_shader *shader;
3804 struct wined3d_sampler *sampler;
3805 const DWORD *tex_unit_map;
3807 if (!(shader = state->shader[shader_type]))
3808 return;
3810 tex_unit_map = context_get_tex_unit_mapping(context,
3811 &shader->reg_maps.shader_version, &base, &count);
3813 shader_sampler_count = shader->reg_maps.sampler_map.count;
3814 if (shader_sampler_count > count)
3815 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3816 shader, shader_sampler_count, count);
3817 count = min(shader_sampler_count, count);
3819 for (i = 0; i < count; ++i)
3821 entry = &shader->reg_maps.sampler_map.entries[i];
3822 bind_idx = base + entry->bind_idx;
3823 if (tex_unit_map)
3824 bind_idx = tex_unit_map[bind_idx];
3826 if (!(view = state->shader_resource_view[shader_type][entry->resource_idx]))
3828 WARN("No resource view bound at index %u, %u.\n", shader_type, entry->resource_idx);
3829 continue;
3832 if (entry->sampler_idx == WINED3D_SAMPLER_DEFAULT)
3833 sampler = device->default_sampler;
3834 else if (!(sampler = state->sampler[shader_type][entry->sampler_idx]))
3835 sampler = device->null_sampler;
3836 wined3d_shader_resource_view_gl_bind(wined3d_shader_resource_view_gl(view), bind_idx, sampler, context);
3840 static void context_load_unordered_access_resources(struct wined3d_context *context,
3841 const struct wined3d_shader *shader, struct wined3d_unordered_access_view * const *views)
3843 struct wined3d_unordered_access_view *view;
3844 struct wined3d_texture *texture;
3845 struct wined3d_buffer *buffer;
3846 unsigned int i;
3848 context->uses_uavs = 0;
3850 if (!shader)
3851 return;
3853 for (i = 0; i < MAX_UNORDERED_ACCESS_VIEWS; ++i)
3855 if (!(view = views[i]))
3856 continue;
3858 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3860 buffer = buffer_from_resource(view->resource);
3861 wined3d_buffer_load_location(buffer, context, WINED3D_LOCATION_BUFFER);
3862 wined3d_unordered_access_view_invalidate_location(view, ~WINED3D_LOCATION_BUFFER);
3864 else
3866 texture = texture_from_resource(view->resource);
3867 wined3d_texture_load(texture, context, FALSE);
3868 wined3d_unordered_access_view_invalidate_location(view, ~WINED3D_LOCATION_TEXTURE_RGB);
3871 context->uses_uavs = 1;
3875 static void context_bind_unordered_access_views(struct wined3d_context *context,
3876 const struct wined3d_shader *shader, struct wined3d_unordered_access_view * const *views)
3878 const struct wined3d_gl_info *gl_info = context->gl_info;
3879 struct wined3d_unordered_access_view_gl *view_gl;
3880 const struct wined3d_format_gl *format_gl;
3881 GLuint texture_name;
3882 unsigned int i;
3883 GLint level;
3885 if (!shader)
3886 return;
3888 for (i = 0; i < MAX_UNORDERED_ACCESS_VIEWS; ++i)
3890 if (!views[i])
3892 if (shader->reg_maps.uav_resource_info[i].type)
3893 WARN("No unordered access view bound at index %u.\n", i);
3894 GL_EXTCALL(glBindImageTexture(i, 0, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8));
3895 continue;
3898 view_gl = wined3d_unordered_access_view_gl(views[i]);
3899 if (view_gl->gl_view.name)
3901 texture_name = view_gl->gl_view.name;
3902 level = 0;
3904 else if (view_gl->v.resource->type != WINED3D_RTYPE_BUFFER)
3906 struct wined3d_texture_gl *texture_gl = wined3d_texture_gl(texture_from_resource(view_gl->v.resource));
3907 texture_name = wined3d_texture_gl_get_texture_name(texture_gl, context, FALSE);
3908 level = view_gl->v.desc.u.texture.level_idx;
3910 else
3912 FIXME("Unsupported buffer unordered access view.\n");
3913 GL_EXTCALL(glBindImageTexture(i, 0, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8));
3914 continue;
3917 format_gl = wined3d_format_gl(view_gl->v.format);
3918 GL_EXTCALL(glBindImageTexture(i, texture_name, level, GL_TRUE, 0, GL_READ_WRITE,
3919 format_gl->internal));
3921 if (view_gl->counter_bo)
3922 GL_EXTCALL(glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, i, view_gl->counter_bo));
3924 checkGLcall("Bind unordered access views");
3927 static void context_load_stream_output_buffers(struct wined3d_context *context,
3928 const struct wined3d_state *state)
3930 unsigned int i;
3932 for (i = 0; i < ARRAY_SIZE(state->stream_output); ++i)
3934 struct wined3d_buffer *buffer;
3935 if (!(buffer = state->stream_output[i].buffer))
3936 continue;
3938 wined3d_buffer_load(buffer, context, state);
3939 wined3d_buffer_invalidate_location(buffer, ~WINED3D_LOCATION_BUFFER);
3943 /* Context activation is done by the caller. */
3944 static BOOL context_apply_draw_state(struct wined3d_context *context,
3945 const struct wined3d_device *device, const struct wined3d_state *state)
3947 const struct StateEntry *state_table = context->state_table;
3948 const struct wined3d_gl_info *gl_info = context->gl_info;
3949 const struct wined3d_fb_state *fb = state->fb;
3950 unsigned int i;
3951 WORD map;
3953 if (!have_framebuffer_attachment(gl_info->limits.buffers, fb->render_targets, fb->depth_stencil))
3955 if (!gl_info->supported[ARB_FRAMEBUFFER_NO_ATTACHMENTS])
3957 FIXME("OpenGL implementation does not support framebuffers with no attachments.\n");
3958 return FALSE;
3961 context_set_render_offscreen(context, TRUE);
3964 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3966 context_validate_onscreen_formats(context, fb->depth_stencil);
3969 /* Preload resources before FBO setup. Texture preload in particular may
3970 * result in changes to the current FBO, due to using e.g. FBO blits for
3971 * updating a resource location. */
3972 context_update_tex_unit_map(context, state);
3973 context_preload_textures(context, state);
3974 context_load_shader_resources(context, state, ~(1u << WINED3D_SHADER_TYPE_COMPUTE));
3975 context_load_unordered_access_resources(context, state->shader[WINED3D_SHADER_TYPE_PIXEL],
3976 state->unordered_access_view[WINED3D_PIPELINE_GRAPHICS]);
3977 context_load_stream_output_buffers(context, state);
3978 /* TODO: Right now the dependency on the vertex shader is necessary
3979 * since wined3d_stream_info_from_declaration() depends on the reg_maps of
3980 * the current VS but maybe it's possible to relax the coupling in some
3981 * situations at least. */
3982 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3983 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3985 context_update_stream_info(context, state);
3987 else
3989 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3991 if (map & 1)
3992 wined3d_buffer_load(state->streams[context->stream_info.elements[i].stream_idx].buffer,
3993 context, state);
3995 /* Loading the buffers above may have invalidated the stream info. */
3996 if (isStateDirty(context, STATE_STREAMSRC))
3997 context_update_stream_info(context, state);
3999 if (state->index_buffer)
4001 if (context->stream_info.all_vbo)
4002 wined3d_buffer_load(state->index_buffer, context, state);
4003 else
4004 wined3d_buffer_load_sysmem(state->index_buffer, context);
4007 for (i = 0; i < context->numDirtyEntries; ++i)
4009 DWORD rep = context->dirtyArray[i];
4010 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
4011 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
4012 context->isStateDirty[idx] &= ~(1u << shift);
4013 state_table[rep].apply(context, state, rep);
4016 if (context->shader_update_mask & ~(1u << WINED3D_SHADER_TYPE_COMPUTE))
4018 device->shader_backend->shader_select(device->shader_priv, context, state);
4019 context->shader_update_mask &= 1u << WINED3D_SHADER_TYPE_COMPUTE;
4022 if (context->constant_update_mask)
4024 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
4025 context->constant_update_mask = 0;
4028 if (context->update_shader_resource_bindings)
4030 for (i = 0; i < WINED3D_SHADER_TYPE_GRAPHICS_COUNT; ++i)
4031 context_bind_shader_resources(context, state, i);
4032 context->update_shader_resource_bindings = 0;
4033 if (gl_info->limits.combined_samplers == gl_info->limits.graphics_samplers)
4034 context->update_compute_shader_resource_bindings = 1;
4037 if (context->update_unordered_access_view_bindings)
4039 context_bind_unordered_access_views(context,
4040 state->shader[WINED3D_SHADER_TYPE_PIXEL],
4041 state->unordered_access_view[WINED3D_PIPELINE_GRAPHICS]);
4042 context->update_unordered_access_view_bindings = 0;
4043 context->update_compute_unordered_access_view_bindings = 1;
4046 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
4048 context_check_fbo_status(context, GL_FRAMEBUFFER);
4051 context->numDirtyEntries = 0; /* This makes the whole list clean */
4052 context->last_was_blit = FALSE;
4053 context->last_was_ffp_blit = FALSE;
4055 return TRUE;
4058 static void context_apply_compute_state(struct wined3d_context *context,
4059 const struct wined3d_device *device, const struct wined3d_state *state)
4061 const struct StateEntry *state_table = context->state_table;
4062 const struct wined3d_gl_info *gl_info = context->gl_info;
4063 unsigned int state_id, i;
4065 context_load_shader_resources(context, state, 1u << WINED3D_SHADER_TYPE_COMPUTE);
4066 context_load_unordered_access_resources(context, state->shader[WINED3D_SHADER_TYPE_COMPUTE],
4067 state->unordered_access_view[WINED3D_PIPELINE_COMPUTE]);
4069 for (i = 0, state_id = STATE_COMPUTE_OFFSET; i < ARRAY_SIZE(context->dirty_compute_states); ++i)
4071 unsigned int dirty_mask = context->dirty_compute_states[i];
4072 while (dirty_mask)
4074 unsigned int current_state_id = state_id + wined3d_bit_scan(&dirty_mask);
4075 state_table[current_state_id].apply(context, state, current_state_id);
4077 state_id += sizeof(*context->dirty_compute_states) * CHAR_BIT;
4079 memset(context->dirty_compute_states, 0, sizeof(*context->dirty_compute_states));
4081 if (context->shader_update_mask & (1u << WINED3D_SHADER_TYPE_COMPUTE))
4083 device->shader_backend->shader_select_compute(device->shader_priv, context, state);
4084 context->shader_update_mask &= ~(1u << WINED3D_SHADER_TYPE_COMPUTE);
4087 if (context->update_compute_shader_resource_bindings)
4089 context_bind_shader_resources(context, state, WINED3D_SHADER_TYPE_COMPUTE);
4090 context->update_compute_shader_resource_bindings = 0;
4091 if (gl_info->limits.combined_samplers == gl_info->limits.graphics_samplers)
4092 context->update_shader_resource_bindings = 1;
4095 if (context->update_compute_unordered_access_view_bindings)
4097 context_bind_unordered_access_views(context,
4098 state->shader[WINED3D_SHADER_TYPE_COMPUTE],
4099 state->unordered_access_view[WINED3D_PIPELINE_COMPUTE]);
4100 context->update_compute_unordered_access_view_bindings = 0;
4101 context->update_unordered_access_view_bindings = 1;
4104 /* Updates to currently bound render targets aren't necessarily coherent
4105 * between the graphics and compute pipelines. Unbind any currently bound
4106 * FBO here to ensure preceding updates to its attachments by the graphics
4107 * pipeline are visible to the compute pipeline.
4109 * Without this, the bloom effect in Nier:Automata is too bright on the
4110 * Mesa radeonsi driver, and presumably on other Mesa based drivers. */
4111 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
4112 context_invalidate_state(context, STATE_FRAMEBUFFER);
4114 context->last_was_blit = FALSE;
4115 context->last_was_ffp_blit = FALSE;
4118 static BOOL use_transform_feedback(const struct wined3d_state *state)
4120 const struct wined3d_shader *shader;
4121 if (!(shader = state->shader[WINED3D_SHADER_TYPE_GEOMETRY]))
4122 return FALSE;
4123 return shader->u.gs.so_desc.element_count;
4126 void context_end_transform_feedback(struct wined3d_context *context)
4128 const struct wined3d_gl_info *gl_info = context->gl_info;
4129 if (context->transform_feedback_active)
4131 GL_EXTCALL(glEndTransformFeedback());
4132 checkGLcall("glEndTransformFeedback");
4133 context->transform_feedback_active = 0;
4134 context->transform_feedback_paused = 0;
4138 static void context_pause_transform_feedback(struct wined3d_context *context, BOOL force)
4140 const struct wined3d_gl_info *gl_info = context->gl_info;
4142 if (!context->transform_feedback_active || context->transform_feedback_paused)
4143 return;
4145 if (gl_info->supported[ARB_TRANSFORM_FEEDBACK2])
4147 GL_EXTCALL(glPauseTransformFeedback());
4148 checkGLcall("glPauseTransformFeedback");
4149 context->transform_feedback_paused = 1;
4150 return;
4153 WARN("Cannot pause transform feedback operations.\n");
4155 if (force)
4156 context_end_transform_feedback(context);
4159 static void context_setup_target(struct wined3d_context *context,
4160 struct wined3d_texture *texture, unsigned int sub_resource_idx)
4162 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
4164 render_offscreen = wined3d_resource_is_offscreen(&texture->resource);
4165 if (context->current_rt.texture == texture
4166 && context->current_rt.sub_resource_idx == sub_resource_idx
4167 && render_offscreen == old_render_offscreen)
4168 return;
4170 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
4171 * the alpha blend state changes with different render target formats. */
4172 if (!context->current_rt.texture)
4174 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
4176 else
4178 const struct wined3d_format *old = context->current_rt.texture->resource.format;
4179 const struct wined3d_format *new = texture->resource.format;
4181 if (old->id != new->id)
4183 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
4184 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
4185 || !(texture->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
4186 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
4188 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
4189 if ((context->current_rt.texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
4190 != (texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
4191 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
4194 /* When switching away from an offscreen render target, and we're not
4195 * using FBOs, we have to read the drawable into the texture. This is
4196 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
4197 * There are some things that need care though. PreLoad needs a GL context,
4198 * and FindContext is called before the context is activated. It also
4199 * has to be called with the old rendertarget active, otherwise a
4200 * wrong drawable is read. */
4201 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
4202 && old_render_offscreen && (context->current_rt.texture != texture
4203 || context->current_rt.sub_resource_idx != sub_resource_idx))
4205 struct wined3d_texture_gl *prev_texture = wined3d_texture_gl(context->current_rt.texture);
4206 unsigned int prev_sub_resource_idx = context->current_rt.sub_resource_idx;
4208 /* Read the back buffer of the old drawable into the destination texture. */
4209 if (prev_texture->texture_srgb.name)
4210 wined3d_texture_load(&prev_texture->t, context, TRUE);
4211 wined3d_texture_load(&prev_texture->t, context, FALSE);
4212 wined3d_texture_invalidate_location(&prev_texture->t, prev_sub_resource_idx, WINED3D_LOCATION_DRAWABLE);
4216 context->current_rt.texture = texture;
4217 context->current_rt.sub_resource_idx = sub_resource_idx;
4218 context_set_render_offscreen(context, render_offscreen);
4221 static void context_activate(struct wined3d_context *context,
4222 struct wined3d_texture *texture, unsigned int sub_resource_idx)
4224 context_enter(context);
4225 context_update_window(context);
4226 context_setup_target(context, texture, sub_resource_idx);
4227 if (!context->valid)
4228 return;
4230 if (context != context_get_current())
4232 if (!context_set_current(context))
4233 ERR("Failed to activate the new context.\n");
4235 else if (context->needs_set)
4237 context_set_gl_context(context);
4241 struct wined3d_context *context_acquire(const struct wined3d_device *device,
4242 struct wined3d_texture *texture, unsigned int sub_resource_idx)
4244 struct wined3d_context *current_context = context_get_current();
4245 struct wined3d_context *context;
4246 BOOL swapchain_texture;
4248 TRACE("device %p, texture %p, sub_resource_idx %u.\n", device, texture, sub_resource_idx);
4250 wined3d_from_cs(device->cs);
4252 if (current_context && current_context->destroyed)
4253 current_context = NULL;
4255 swapchain_texture = texture && texture->swapchain;
4256 if (!texture)
4258 if (current_context
4259 && current_context->current_rt.texture
4260 && current_context->device == device)
4262 texture = current_context->current_rt.texture;
4263 sub_resource_idx = current_context->current_rt.sub_resource_idx;
4265 else
4267 struct wined3d_swapchain *swapchain = device->swapchains[0];
4269 if (swapchain->back_buffers)
4270 texture = swapchain->back_buffers[0];
4271 else
4272 texture = swapchain->front_buffer;
4273 sub_resource_idx = 0;
4277 if (current_context && current_context->current_rt.texture == texture)
4279 context = current_context;
4281 else if (swapchain_texture)
4283 TRACE("Rendering onscreen.\n");
4285 context = swapchain_get_context(texture->swapchain);
4287 else
4289 TRACE("Rendering offscreen.\n");
4291 /* Stay with the current context if possible. Otherwise use the
4292 * context for the primary swapchain. */
4293 if (current_context && current_context->device == device)
4294 context = current_context;
4295 else
4296 context = swapchain_get_context(device->swapchains[0]);
4299 context_activate(context, texture, sub_resource_idx);
4301 return context;
4304 struct wined3d_context *context_reacquire(const struct wined3d_device *device,
4305 struct wined3d_context *context)
4307 struct wined3d_context *acquired_context;
4309 wined3d_from_cs(device->cs);
4311 if (!context || context->tid != GetCurrentThreadId())
4312 return NULL;
4314 if (context->current_rt.texture)
4316 context_activate(context, context->current_rt.texture, context->current_rt.sub_resource_idx);
4317 return context;
4320 acquired_context = context_acquire(device, NULL, 0);
4321 if (acquired_context != context)
4322 ERR("Acquired context %p instead of %p.\n", acquired_context, context);
4323 return acquired_context;
4326 void dispatch_compute(struct wined3d_device *device, const struct wined3d_state *state,
4327 const struct wined3d_dispatch_parameters *parameters)
4329 const struct wined3d_gl_info *gl_info;
4330 struct wined3d_context *context;
4332 context = context_acquire(device, NULL, 0);
4333 if (!context->valid)
4335 context_release(context);
4336 WARN("Invalid context, skipping dispatch.\n");
4337 return;
4339 gl_info = context->gl_info;
4341 if (!gl_info->supported[ARB_COMPUTE_SHADER])
4343 context_release(context);
4344 FIXME("OpenGL implementation does not support compute shaders.\n");
4345 return;
4348 if (parameters->indirect)
4349 wined3d_buffer_load(parameters->u.indirect.buffer, context, state);
4351 context_apply_compute_state(context, device, state);
4353 if (!state->shader[WINED3D_SHADER_TYPE_COMPUTE])
4355 context_release(context);
4356 WARN("No compute shader bound, skipping dispatch.\n");
4357 return;
4360 if (parameters->indirect)
4362 const struct wined3d_indirect_dispatch_parameters *indirect = &parameters->u.indirect;
4363 struct wined3d_buffer *buffer = indirect->buffer;
4365 GL_EXTCALL(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, wined3d_buffer_gl(buffer)->buffer_object));
4366 GL_EXTCALL(glDispatchComputeIndirect((GLintptr)indirect->offset));
4367 GL_EXTCALL(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0));
4369 else
4371 const struct wined3d_direct_dispatch_parameters *direct = &parameters->u.direct;
4372 GL_EXTCALL(glDispatchCompute(direct->group_count_x, direct->group_count_y, direct->group_count_z));
4374 checkGLcall("dispatch compute");
4376 GL_EXTCALL(glMemoryBarrier(GL_ALL_BARRIER_BITS));
4377 checkGLcall("glMemoryBarrier");
4379 context_release(context);
4382 /* Context activation is done by the caller. */
4383 static void draw_primitive_arrays(struct wined3d_context *context, const struct wined3d_state *state,
4384 const void *idx_data, unsigned int idx_size, int base_vertex_idx, unsigned int start_idx,
4385 unsigned int count, unsigned int start_instance, unsigned int instance_count)
4387 const struct wined3d_ffp_attrib_ops *ops = &context->d3d_info->ffp_attrib_ops;
4388 GLenum idx_type = idx_size == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
4389 const struct wined3d_stream_info *si = &context->stream_info;
4390 unsigned int instanced_elements[ARRAY_SIZE(si->elements)];
4391 const struct wined3d_gl_info *gl_info = context->gl_info;
4392 unsigned int instanced_element_count = 0;
4393 GLenum mode = state->gl_primitive_type;
4394 const void *indices;
4395 unsigned int i, j;
4397 indices = (const char *)idx_data + idx_size * start_idx;
4399 if (!instance_count)
4401 if (!idx_size)
4403 gl_info->gl_ops.gl.p_glDrawArrays(mode, start_idx, count);
4404 checkGLcall("glDrawArrays");
4405 return;
4408 if (gl_info->supported[ARB_DRAW_ELEMENTS_BASE_VERTEX])
4410 GL_EXTCALL(glDrawElementsBaseVertex(mode, count, idx_type, indices, base_vertex_idx));
4411 checkGLcall("glDrawElementsBaseVertex");
4412 return;
4415 gl_info->gl_ops.gl.p_glDrawElements(mode, count, idx_type, indices);
4416 checkGLcall("glDrawElements");
4417 return;
4420 if (start_instance && !(gl_info->supported[ARB_BASE_INSTANCE] && gl_info->supported[ARB_INSTANCED_ARRAYS]))
4421 FIXME("Start instance (%u) not supported.\n", start_instance);
4423 if (gl_info->supported[ARB_INSTANCED_ARRAYS])
4425 if (!idx_size)
4427 if (gl_info->supported[ARB_BASE_INSTANCE])
4429 GL_EXTCALL(glDrawArraysInstancedBaseInstance(mode, start_idx, count, instance_count, start_instance));
4430 checkGLcall("glDrawArraysInstancedBaseInstance");
4431 return;
4434 GL_EXTCALL(glDrawArraysInstanced(mode, start_idx, count, instance_count));
4435 checkGLcall("glDrawArraysInstanced");
4436 return;
4439 if (gl_info->supported[ARB_BASE_INSTANCE])
4441 GL_EXTCALL(glDrawElementsInstancedBaseVertexBaseInstance(mode, count, idx_type,
4442 indices, instance_count, base_vertex_idx, start_instance));
4443 checkGLcall("glDrawElementsInstancedBaseVertexBaseInstance");
4444 return;
4446 if (gl_info->supported[ARB_DRAW_ELEMENTS_BASE_VERTEX])
4448 GL_EXTCALL(glDrawElementsInstancedBaseVertex(mode, count, idx_type,
4449 indices, instance_count, base_vertex_idx));
4450 checkGLcall("glDrawElementsInstancedBaseVertex");
4451 return;
4454 GL_EXTCALL(glDrawElementsInstanced(mode, count, idx_type, indices, instance_count));
4455 checkGLcall("glDrawElementsInstanced");
4456 return;
4459 /* Instancing emulation by mixing immediate mode and arrays. */
4461 /* This is a nasty thing. MSDN says no hardware supports this and
4462 * applications have to use software vertex processing. We don't support
4463 * this for now.
4465 * Shouldn't be too hard to support with OpenGL, in theory just call
4466 * glDrawArrays() instead of drawElements(). But the stream fequency value
4467 * has a different meaning in that situation. */
4468 if (!idx_size)
4470 FIXME("Non-indexed instanced drawing is not supported.\n");
4471 return;
4474 for (i = 0; i < ARRAY_SIZE(si->elements); ++i)
4476 if (!(si->use_map & (1u << i)))
4477 continue;
4479 if (state->streams[si->elements[i].stream_idx].flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
4480 instanced_elements[instanced_element_count++] = i;
4483 for (i = 0; i < instance_count; ++i)
4485 /* Specify the instanced attributes using immediate mode calls. */
4486 for (j = 0; j < instanced_element_count; ++j)
4488 const struct wined3d_stream_info_element *element;
4489 unsigned int element_idx;
4490 const BYTE *ptr;
4492 element_idx = instanced_elements[j];
4493 element = &si->elements[element_idx];
4494 ptr = element->data.addr + element->stride * i;
4495 if (element->data.buffer_object)
4496 ptr += (ULONG_PTR)wined3d_buffer_load_sysmem(state->streams[element->stream_idx].buffer, context);
4497 ops->generic[element->format->emit_idx](element_idx, ptr);
4500 if (gl_info->supported[ARB_DRAW_ELEMENTS_BASE_VERTEX])
4502 GL_EXTCALL(glDrawElementsBaseVertex(mode, count, idx_type, indices, base_vertex_idx));
4503 checkGLcall("glDrawElementsBaseVertex");
4505 else
4507 gl_info->gl_ops.gl.p_glDrawElements(mode, count, idx_type, indices);
4508 checkGLcall("glDrawElements");
4513 static unsigned int get_stride_idx(const void *idx_data, unsigned int idx_size,
4514 unsigned int base_vertex_idx, unsigned int start_idx, unsigned int vertex_idx)
4516 if (!idx_data)
4517 return start_idx + vertex_idx;
4518 if (idx_size == 2)
4519 return ((const WORD *)idx_data)[start_idx + vertex_idx] + base_vertex_idx;
4520 return ((const DWORD *)idx_data)[start_idx + vertex_idx] + base_vertex_idx;
4523 /* Context activation is done by the caller. */
4524 static void draw_primitive_immediate_mode(struct wined3d_context *context, const struct wined3d_state *state,
4525 const struct wined3d_stream_info *si, const void *idx_data, unsigned int idx_size,
4526 int base_vertex_idx, unsigned int start_idx, unsigned int vertex_count, unsigned int instance_count)
4528 const BYTE *position = NULL, *normal = NULL, *diffuse = NULL, *specular = NULL;
4529 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
4530 unsigned int coord_idx, stride_idx, texture_idx, vertex_idx;
4531 const struct wined3d_gl_info *gl_info = context->gl_info;
4532 const struct wined3d_stream_info_element *element;
4533 const BYTE *tex_coords[WINED3DDP_MAXTEXCOORD];
4534 unsigned int texture_unit, texture_stages;
4535 const struct wined3d_ffp_attrib_ops *ops;
4536 unsigned int untracked_material_count;
4537 unsigned int tex_mask = 0;
4538 BOOL specular_fog = FALSE;
4539 BOOL ps = use_ps(state);
4540 const void *ptr;
4542 static unsigned int once;
4544 if (!once++)
4545 FIXME_(d3d_perf)("Drawing using immediate mode.\n");
4546 else
4547 WARN_(d3d_perf)("Drawing using immediate mode.\n");
4549 if (!idx_size && idx_data)
4550 ERR("Non-NULL idx_data with 0 idx_size, this should never happen.\n");
4552 if (instance_count)
4553 FIXME("Instancing not implemented.\n");
4555 /* Immediate mode drawing can't make use of indices in a VBO - get the
4556 * data from the index buffer. */
4557 if (idx_size)
4558 idx_data = wined3d_buffer_load_sysmem(state->index_buffer, context) + state->index_offset;
4560 ops = &d3d_info->ffp_attrib_ops;
4562 gl_info->gl_ops.gl.p_glBegin(state->gl_primitive_type);
4564 if (use_vs(state) || d3d_info->ffp_generic_attributes)
4566 for (vertex_idx = 0; vertex_idx < vertex_count; ++vertex_idx)
4568 unsigned int use_map = si->use_map;
4569 unsigned int element_idx;
4571 stride_idx = get_stride_idx(idx_data, idx_size, base_vertex_idx, start_idx, vertex_idx);
4572 for (element_idx = MAX_ATTRIBS - 1; use_map; use_map &= ~(1u << element_idx), --element_idx)
4574 if (!(use_map & 1u << element_idx))
4575 continue;
4577 ptr = si->elements[element_idx].data.addr + si->elements[element_idx].stride * stride_idx;
4578 ops->generic[si->elements[element_idx].format->emit_idx](element_idx, ptr);
4582 gl_info->gl_ops.gl.p_glEnd();
4583 return;
4586 if (si->use_map & (1u << WINED3D_FFP_POSITION))
4587 position = si->elements[WINED3D_FFP_POSITION].data.addr;
4589 if (si->use_map & (1u << WINED3D_FFP_NORMAL))
4590 normal = si->elements[WINED3D_FFP_NORMAL].data.addr;
4591 else
4592 gl_info->gl_ops.gl.p_glNormal3f(0.0f, 0.0f, 0.0f);
4594 untracked_material_count = context->num_untracked_materials;
4595 if (si->use_map & (1u << WINED3D_FFP_DIFFUSE))
4597 element = &si->elements[WINED3D_FFP_DIFFUSE];
4598 diffuse = element->data.addr;
4600 if (untracked_material_count && element->format->id != WINED3DFMT_B8G8R8A8_UNORM)
4601 FIXME("Implement diffuse color tracking from %s.\n", debug_d3dformat(element->format->id));
4603 else
4605 gl_info->gl_ops.gl.p_glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
4608 if (si->use_map & (1u << WINED3D_FFP_SPECULAR))
4610 element = &si->elements[WINED3D_FFP_SPECULAR];
4611 specular = element->data.addr;
4613 /* Special case where the fog density is stored in the specular alpha channel. */
4614 if (state->render_states[WINED3D_RS_FOGENABLE]
4615 && (state->render_states[WINED3D_RS_FOGVERTEXMODE] == WINED3D_FOG_NONE
4616 || si->elements[WINED3D_FFP_POSITION].format->id == WINED3DFMT_R32G32B32A32_FLOAT)
4617 && state->render_states[WINED3D_RS_FOGTABLEMODE] == WINED3D_FOG_NONE)
4619 if (gl_info->supported[EXT_FOG_COORD])
4621 if (element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
4622 specular_fog = TRUE;
4623 else
4624 FIXME("Implement fog coordinates from %s.\n", debug_d3dformat(element->format->id));
4626 else
4628 static unsigned int once;
4630 if (!once++)
4631 FIXME("Implement fog for transformed vertices in software.\n");
4635 else if (gl_info->supported[EXT_SECONDARY_COLOR])
4637 GL_EXTCALL(glSecondaryColor3fEXT)(0.0f, 0.0f, 0.0f);
4640 texture_stages = d3d_info->limits.ffp_blend_stages;
4641 for (texture_idx = 0; texture_idx < texture_stages; ++texture_idx)
4643 if (!gl_info->supported[ARB_MULTITEXTURE] && texture_idx > 0)
4645 FIXME("Program using multiple concurrent textures which this OpenGL implementation doesn't support.\n");
4646 continue;
4649 if (!ps && !state->textures[texture_idx])
4650 continue;
4652 texture_unit = context->tex_unit_map[texture_idx];
4653 if (texture_unit == WINED3D_UNMAPPED_STAGE)
4654 continue;
4656 coord_idx = state->texture_states[texture_idx][WINED3D_TSS_TEXCOORD_INDEX];
4657 if (coord_idx > 7)
4659 TRACE("Skipping generated coordinates (%#x) for texture %u.\n", coord_idx, texture_idx);
4660 continue;
4663 if (si->use_map & (1u << (WINED3D_FFP_TEXCOORD0 + coord_idx)))
4665 tex_coords[coord_idx] = si->elements[WINED3D_FFP_TEXCOORD0 + coord_idx].data.addr;
4666 tex_mask |= (1u << texture_idx);
4668 else
4670 TRACE("Setting default coordinates for texture %u.\n", texture_idx);
4671 if (gl_info->supported[ARB_MULTITEXTURE])
4672 GL_EXTCALL(glMultiTexCoord4fARB(GL_TEXTURE0_ARB + texture_unit, 0.0f, 0.0f, 0.0f, 1.0f));
4673 else
4674 gl_info->gl_ops.gl.p_glTexCoord4f(0.0f, 0.0f, 0.0f, 1.0f);
4678 /* Blending data and point sizes are not supported by this function. They
4679 * are not supported by the fixed function pipeline at all. A FIXME for
4680 * them is printed after decoding the vertex declaration. */
4681 for (vertex_idx = 0; vertex_idx < vertex_count; ++vertex_idx)
4683 unsigned int tmp_tex_mask;
4685 stride_idx = get_stride_idx(idx_data, idx_size, base_vertex_idx, start_idx, vertex_idx);
4687 if (normal)
4689 ptr = normal + stride_idx * si->elements[WINED3D_FFP_NORMAL].stride;
4690 ops->normal[si->elements[WINED3D_FFP_NORMAL].format->emit_idx](ptr);
4693 if (diffuse)
4695 ptr = diffuse + stride_idx * si->elements[WINED3D_FFP_DIFFUSE].stride;
4696 ops->diffuse[si->elements[WINED3D_FFP_DIFFUSE].format->emit_idx](ptr);
4698 if (untracked_material_count)
4700 struct wined3d_color color;
4701 unsigned int i;
4703 wined3d_color_from_d3dcolor(&color, *(const DWORD *)ptr);
4704 for (i = 0; i < untracked_material_count; ++i)
4706 gl_info->gl_ops.gl.p_glMaterialfv(GL_FRONT_AND_BACK, context->untracked_materials[i], &color.r);
4711 if (specular)
4713 ptr = specular + stride_idx * si->elements[WINED3D_FFP_SPECULAR].stride;
4714 ops->specular[si->elements[WINED3D_FFP_SPECULAR].format->emit_idx](ptr);
4716 if (specular_fog)
4717 GL_EXTCALL(glFogCoordfEXT((float)(*(const DWORD *)ptr >> 24)));
4720 tmp_tex_mask = tex_mask;
4721 for (texture_idx = 0; tmp_tex_mask; tmp_tex_mask >>= 1, ++texture_idx)
4723 if (!(tmp_tex_mask & 1))
4724 continue;
4726 coord_idx = state->texture_states[texture_idx][WINED3D_TSS_TEXCOORD_INDEX];
4727 ptr = tex_coords[coord_idx] + (stride_idx * si->elements[WINED3D_FFP_TEXCOORD0 + coord_idx].stride);
4728 ops->texcoord[si->elements[WINED3D_FFP_TEXCOORD0 + coord_idx].format->emit_idx](
4729 GL_TEXTURE0_ARB + context->tex_unit_map[texture_idx], ptr);
4732 if (position)
4734 ptr = position + stride_idx * si->elements[WINED3D_FFP_POSITION].stride;
4735 ops->position[si->elements[WINED3D_FFP_POSITION].format->emit_idx](ptr);
4739 gl_info->gl_ops.gl.p_glEnd();
4740 checkGLcall("draw immediate mode");
4743 static void draw_indirect(struct wined3d_context *context, const struct wined3d_state *state,
4744 const struct wined3d_indirect_draw_parameters *parameters, unsigned int idx_size)
4746 const struct wined3d_gl_info *gl_info = context->gl_info;
4747 struct wined3d_buffer *buffer = parameters->buffer;
4748 const void *offset;
4750 if (!gl_info->supported[ARB_DRAW_INDIRECT])
4752 FIXME("OpenGL implementation does not support indirect draws.\n");
4753 return;
4756 GL_EXTCALL(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, wined3d_buffer_gl(buffer)->buffer_object));
4758 offset = (void *)(GLintptr)parameters->offset;
4759 if (idx_size)
4761 GLenum idx_type = idx_size == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
4762 if (state->index_offset)
4763 FIXME("Ignoring index offset %u.\n", state->index_offset);
4764 GL_EXTCALL(glDrawElementsIndirect(state->gl_primitive_type, idx_type, offset));
4766 else
4768 GL_EXTCALL(glDrawArraysIndirect(state->gl_primitive_type, offset));
4771 GL_EXTCALL(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0));
4773 checkGLcall("draw indirect");
4776 static void remove_vbos(struct wined3d_context *context,
4777 const struct wined3d_state *state, struct wined3d_stream_info *s)
4779 unsigned int i;
4781 for (i = 0; i < ARRAY_SIZE(s->elements); ++i)
4783 struct wined3d_stream_info_element *e;
4785 if (!(s->use_map & (1u << i)))
4786 continue;
4788 e = &s->elements[i];
4789 if (e->data.buffer_object)
4791 struct wined3d_buffer *vb = state->streams[e->stream_idx].buffer;
4792 e->data.buffer_object = 0;
4793 e->data.addr += (ULONG_PTR)wined3d_buffer_load_sysmem(vb, context);
4798 static GLenum gl_tfb_primitive_type_from_d3d(enum wined3d_primitive_type primitive_type)
4800 GLenum gl_primitive_type = gl_primitive_type_from_d3d(primitive_type);
4801 switch (gl_primitive_type)
4803 case GL_POINTS:
4804 return GL_POINTS;
4806 case GL_LINE_STRIP:
4807 case GL_LINE_STRIP_ADJACENCY:
4808 case GL_LINES_ADJACENCY:
4809 case GL_LINES:
4810 return GL_LINES;
4812 case GL_TRIANGLE_FAN:
4813 case GL_TRIANGLE_STRIP:
4814 case GL_TRIANGLE_STRIP_ADJACENCY:
4815 case GL_TRIANGLES_ADJACENCY:
4816 case GL_TRIANGLES:
4817 return GL_TRIANGLES;
4819 default:
4820 return gl_primitive_type;
4824 /* Routine common to the draw primitive and draw indexed primitive routines */
4825 void draw_primitive(struct wined3d_device *device, const struct wined3d_state *state,
4826 const struct wined3d_draw_parameters *parameters)
4828 BOOL emulation = FALSE, rasterizer_discard = FALSE;
4829 const struct wined3d_fb_state *fb = state->fb;
4830 const struct wined3d_stream_info *stream_info;
4831 struct wined3d_rendertarget_view *dsv, *rtv;
4832 struct wined3d_stream_info si_emulated;
4833 struct wined3d_fence *ib_fence = NULL;
4834 const struct wined3d_gl_info *gl_info;
4835 struct wined3d_context *context;
4836 unsigned int i, idx_size = 0;
4837 const void *idx_data = NULL;
4839 if (!parameters->indirect && !parameters->u.direct.index_count)
4840 return;
4842 if (!(rtv = fb->render_targets[0]))
4843 rtv = fb->depth_stencil;
4845 if (rtv && rtv->resource->type == WINED3D_RTYPE_BUFFER)
4847 FIXME("Buffer render targets not implemented.\n");
4848 return;
4851 if (rtv)
4852 context = context_acquire(device, wined3d_texture_from_resource(rtv->resource), rtv->sub_resource_idx);
4853 else
4854 context = context_acquire(device, NULL, 0);
4855 if (!context->valid)
4857 context_release(context);
4858 WARN("Invalid context, skipping draw.\n");
4859 return;
4861 gl_info = context->gl_info;
4863 if (!use_transform_feedback(state))
4864 context_pause_transform_feedback(context, TRUE);
4866 for (i = 0; i < gl_info->limits.buffers; ++i)
4868 if (!(rtv = fb->render_targets[i]) || rtv->format->id == WINED3DFMT_NULL)
4869 continue;
4871 if (state->render_states[WINED3D_RS_COLORWRITEENABLE])
4873 wined3d_rendertarget_view_load_location(rtv, context, rtv->resource->draw_binding);
4874 wined3d_rendertarget_view_invalidate_location(rtv, ~rtv->resource->draw_binding);
4876 else
4878 wined3d_rendertarget_view_prepare_location(rtv, context, rtv->resource->draw_binding);
4882 if ((dsv = fb->depth_stencil))
4884 /* Note that this depends on the context_acquire() call above to set
4885 * context->render_offscreen properly. We don't currently take the
4886 * Z-compare function into account, but we could skip loading the
4887 * depthstencil for D3DCMP_NEVER and D3DCMP_ALWAYS as well. Also note
4888 * that we never copy the stencil data.*/
4889 DWORD location = context->render_offscreen ? dsv->resource->draw_binding : WINED3D_LOCATION_DRAWABLE;
4891 if (state->render_states[WINED3D_RS_ZWRITEENABLE] || state->render_states[WINED3D_RS_ZENABLE])
4892 wined3d_rendertarget_view_load_location(dsv, context, location);
4893 else
4894 wined3d_rendertarget_view_prepare_location(dsv, context, location);
4897 if (parameters->indirect)
4898 wined3d_buffer_load(parameters->u.indirect.buffer, context, state);
4900 if (!context_apply_draw_state(context, device, state))
4902 context_release(context);
4903 WARN("Unable to apply draw state, skipping draw.\n");
4904 return;
4907 if (dsv && state->render_states[WINED3D_RS_ZWRITEENABLE])
4909 DWORD location = context->render_offscreen ? dsv->resource->draw_binding : WINED3D_LOCATION_DRAWABLE;
4911 wined3d_rendertarget_view_validate_location(dsv, location);
4912 wined3d_rendertarget_view_invalidate_location(dsv, ~location);
4915 stream_info = &context->stream_info;
4917 if (parameters->indexed)
4919 struct wined3d_buffer *index_buffer = state->index_buffer;
4920 if (!wined3d_buffer_gl(index_buffer)->buffer_object || !stream_info->all_vbo)
4922 idx_data = index_buffer->resource.heap_memory;
4924 else
4926 ib_fence = index_buffer->fence;
4927 idx_data = NULL;
4929 idx_data = (const BYTE *)idx_data + state->index_offset;
4931 if (state->index_format == WINED3DFMT_R16_UINT)
4932 idx_size = 2;
4933 else
4934 idx_size = 4;
4937 if (!use_vs(state))
4939 if (!stream_info->position_transformed && context->num_untracked_materials
4940 && state->render_states[WINED3D_RS_LIGHTING])
4942 static BOOL warned;
4944 if (!warned++)
4945 FIXME("Using software emulation because not all material properties could be tracked.\n");
4946 else
4947 WARN_(d3d_perf)("Using software emulation because not all material properties could be tracked.\n");
4948 emulation = TRUE;
4950 else if (context->fog_coord && state->render_states[WINED3D_RS_FOGENABLE])
4952 static BOOL warned;
4954 /* Either write a pipeline replacement shader or convert the
4955 * specular alpha from unsigned byte to a float in the vertex
4956 * buffer. */
4957 if (!warned++)
4958 FIXME("Using software emulation because manual fog coordinates are provided.\n");
4959 else
4960 WARN_(d3d_perf)("Using software emulation because manual fog coordinates are provided.\n");
4961 emulation = TRUE;
4964 if (emulation)
4966 si_emulated = context->stream_info;
4967 remove_vbos(context, state, &si_emulated);
4968 stream_info = &si_emulated;
4972 if (use_transform_feedback(state))
4974 const struct wined3d_shader *shader = state->shader[WINED3D_SHADER_TYPE_GEOMETRY];
4976 if (is_rasterization_disabled(shader))
4978 glEnable(GL_RASTERIZER_DISCARD);
4979 checkGLcall("enable rasterizer discard");
4980 rasterizer_discard = TRUE;
4983 if (context->transform_feedback_paused)
4985 GL_EXTCALL(glResumeTransformFeedback());
4986 checkGLcall("glResumeTransformFeedback");
4987 context->transform_feedback_paused = 0;
4989 else if (!context->transform_feedback_active)
4991 enum wined3d_primitive_type primitive_type = shader->u.gs.output_type
4992 ? shader->u.gs.output_type : d3d_primitive_type_from_gl(state->gl_primitive_type);
4993 GLenum mode = gl_tfb_primitive_type_from_d3d(primitive_type);
4994 GL_EXTCALL(glBeginTransformFeedback(mode));
4995 checkGLcall("glBeginTransformFeedback");
4996 context->transform_feedback_active = 1;
5000 if (state->gl_primitive_type == GL_PATCHES)
5002 GL_EXTCALL(glPatchParameteri(GL_PATCH_VERTICES, state->gl_patch_vertices));
5003 checkGLcall("glPatchParameteri");
5006 if (parameters->indirect)
5008 if (!context->use_immediate_mode_draw && !emulation)
5009 draw_indirect(context, state, &parameters->u.indirect, idx_size);
5010 else
5011 FIXME("Indirect draws with immediate mode/emulation are not supported.\n");
5013 else
5015 unsigned int instance_count = parameters->u.direct.instance_count;
5016 if (context->instance_count)
5017 instance_count = context->instance_count;
5019 if (context->use_immediate_mode_draw || emulation)
5020 draw_primitive_immediate_mode(context, state, stream_info, idx_data,
5021 idx_size, parameters->u.direct.base_vertex_idx,
5022 parameters->u.direct.start_idx, parameters->u.direct.index_count, instance_count);
5023 else
5024 draw_primitive_arrays(context, state, idx_data, idx_size, parameters->u.direct.base_vertex_idx,
5025 parameters->u.direct.start_idx, parameters->u.direct.index_count,
5026 parameters->u.direct.start_instance, instance_count);
5029 if (context->uses_uavs)
5031 GL_EXTCALL(glMemoryBarrier(GL_ALL_BARRIER_BITS));
5032 checkGLcall("glMemoryBarrier");
5035 context_pause_transform_feedback(context, FALSE);
5037 if (rasterizer_discard)
5039 glDisable(GL_RASTERIZER_DISCARD);
5040 checkGLcall("disable rasterizer discard");
5043 if (ib_fence)
5044 wined3d_fence_issue(ib_fence, device);
5045 for (i = 0; i < context->buffer_fence_count; ++i)
5046 wined3d_fence_issue(context->buffer_fences[i], device);
5048 context_release(context);
5051 void context_unload_tex_coords(const struct wined3d_context *context)
5053 const struct wined3d_gl_info *gl_info = context->gl_info;
5054 unsigned int texture_idx;
5056 for (texture_idx = 0; texture_idx < gl_info->limits.texture_coords; ++texture_idx)
5058 gl_info->gl_ops.ext.p_glClientActiveTextureARB(GL_TEXTURE0_ARB + texture_idx);
5059 gl_info->gl_ops.gl.p_glDisableClientState(GL_TEXTURE_COORD_ARRAY);
5063 void context_load_tex_coords(const struct wined3d_context *context, const struct wined3d_stream_info *si,
5064 GLuint *current_bo, const struct wined3d_state *state)
5066 const struct wined3d_gl_info *gl_info = context->gl_info;
5067 const struct wined3d_format_gl *format_gl;
5068 unsigned int mapped_stage = 0;
5069 unsigned int texture_idx;
5071 for (texture_idx = 0; texture_idx < context->d3d_info->limits.ffp_blend_stages; ++texture_idx)
5073 unsigned int coord_idx = state->texture_states[texture_idx][WINED3D_TSS_TEXCOORD_INDEX];
5075 if ((mapped_stage = context->tex_unit_map[texture_idx]) == WINED3D_UNMAPPED_STAGE)
5076 continue;
5078 if (mapped_stage >= gl_info->limits.texture_coords)
5080 FIXME("Attempted to load unsupported texture coordinate %u.\n", mapped_stage);
5081 continue;
5084 if (coord_idx < MAX_TEXTURES && (si->use_map & (1u << (WINED3D_FFP_TEXCOORD0 + coord_idx))))
5086 const struct wined3d_stream_info_element *e = &si->elements[WINED3D_FFP_TEXCOORD0 + coord_idx];
5088 TRACE("Setting up texture %u, idx %u, coord_idx %u, data %s.\n",
5089 texture_idx, mapped_stage, coord_idx, debug_bo_address(&e->data));
5091 if (*current_bo != e->data.buffer_object)
5093 GL_EXTCALL(glBindBuffer(GL_ARRAY_BUFFER, e->data.buffer_object));
5094 checkGLcall("glBindBuffer");
5095 *current_bo = e->data.buffer_object;
5098 GL_EXTCALL(glClientActiveTextureARB(GL_TEXTURE0_ARB + mapped_stage));
5099 checkGLcall("glClientActiveTextureARB");
5101 /* The coords to supply depend completely on the fvf/vertex shader. */
5102 format_gl = wined3d_format_gl(e->format);
5103 gl_info->gl_ops.gl.p_glTexCoordPointer(format_gl->vtx_format, format_gl->vtx_type, e->stride,
5104 e->data.addr + state->load_base_vertex_index * e->stride);
5105 gl_info->gl_ops.gl.p_glEnableClientState(GL_TEXTURE_COORD_ARRAY);
5107 else
5109 GL_EXTCALL(glMultiTexCoord4fARB(GL_TEXTURE0_ARB + mapped_stage, 0, 0, 0, 1));
5112 if (gl_info->supported[NV_REGISTER_COMBINERS])
5114 /* The number of the mapped stages increases monotonically, so it's fine to use the last used one. */
5115 for (texture_idx = mapped_stage + 1; texture_idx < gl_info->limits.textures; ++texture_idx)
5117 GL_EXTCALL(glMultiTexCoord4fARB(GL_TEXTURE0_ARB + texture_idx, 0, 0, 0, 1));
5121 checkGLcall("loadTexCoords");
5124 /* This should match any arrays loaded in context_load_vertex_data(). */
5125 static void context_unload_vertex_data(struct wined3d_context *context)
5127 const struct wined3d_gl_info *gl_info = context->gl_info;
5129 if (!context->namedArraysLoaded)
5130 return;
5131 gl_info->gl_ops.gl.p_glDisableClientState(GL_VERTEX_ARRAY);
5132 gl_info->gl_ops.gl.p_glDisableClientState(GL_NORMAL_ARRAY);
5133 gl_info->gl_ops.gl.p_glDisableClientState(GL_COLOR_ARRAY);
5134 if (gl_info->supported[EXT_SECONDARY_COLOR])
5135 gl_info->gl_ops.gl.p_glDisableClientState(GL_SECONDARY_COLOR_ARRAY_EXT);
5136 context_unload_tex_coords(context);
5137 context->namedArraysLoaded = FALSE;
5140 static void context_load_vertex_data(struct wined3d_context *context,
5141 const struct wined3d_stream_info *si, const struct wined3d_state *state)
5143 const struct wined3d_gl_info *gl_info = context->gl_info;
5144 const struct wined3d_stream_info_element *e;
5145 const struct wined3d_format_gl *format_gl;
5146 GLuint current_bo;
5148 TRACE("context %p, si %p, state %p.\n", context, si, state);
5150 /* This is used for the fixed-function pipeline only, and the
5151 * fixed-function pipeline doesn't do instancing. */
5152 context->instance_count = 0;
5153 current_bo = gl_info->supported[ARB_VERTEX_BUFFER_OBJECT] ? ~0u : 0;
5155 /* Blend data */
5156 if ((si->use_map & (1u << WINED3D_FFP_BLENDWEIGHT))
5157 || si->use_map & (1u << WINED3D_FFP_BLENDINDICES))
5159 /* TODO: Support vertex blending in immediate mode draws. No need to
5160 * write a FIXME here, this is done after the general vertex
5161 * declaration decoding. */
5162 WARN("Vertex blending not supported.\n");
5165 /* Point Size */
5166 if (si->use_map & (1u << WINED3D_FFP_PSIZE))
5168 /* No such functionality in the fixed-function GL pipeline. */
5169 WARN("Per-vertex point size not supported.\n");
5172 /* Position */
5173 if (si->use_map & (1u << WINED3D_FFP_POSITION))
5175 e = &si->elements[WINED3D_FFP_POSITION];
5176 format_gl = wined3d_format_gl(e->format);
5178 if (current_bo != e->data.buffer_object)
5180 GL_EXTCALL(glBindBuffer(GL_ARRAY_BUFFER, e->data.buffer_object));
5181 checkGLcall("glBindBuffer");
5182 current_bo = e->data.buffer_object;
5185 TRACE("glVertexPointer(%#x, %#x, %#x, %p);\n",
5186 format_gl->vtx_format, format_gl->vtx_type, e->stride,
5187 e->data.addr + state->load_base_vertex_index * e->stride);
5188 gl_info->gl_ops.gl.p_glVertexPointer(format_gl->vtx_format, format_gl->vtx_type, e->stride,
5189 e->data.addr + state->load_base_vertex_index * e->stride);
5190 checkGLcall("glVertexPointer(...)");
5191 gl_info->gl_ops.gl.p_glEnableClientState(GL_VERTEX_ARRAY);
5192 checkGLcall("glEnableClientState(GL_VERTEX_ARRAY)");
5195 /* Normals */
5196 if (si->use_map & (1u << WINED3D_FFP_NORMAL))
5198 e = &si->elements[WINED3D_FFP_NORMAL];
5199 format_gl = wined3d_format_gl(e->format);
5201 if (current_bo != e->data.buffer_object)
5203 GL_EXTCALL(glBindBuffer(GL_ARRAY_BUFFER, e->data.buffer_object));
5204 checkGLcall("glBindBuffer");
5205 current_bo = e->data.buffer_object;
5208 TRACE("glNormalPointer(%#x, %#x, %p);\n", format_gl->vtx_type, e->stride,
5209 e->data.addr + state->load_base_vertex_index * e->stride);
5210 gl_info->gl_ops.gl.p_glNormalPointer(format_gl->vtx_type, e->stride,
5211 e->data.addr + state->load_base_vertex_index * e->stride);
5212 checkGLcall("glNormalPointer(...)");
5213 gl_info->gl_ops.gl.p_glEnableClientState(GL_NORMAL_ARRAY);
5214 checkGLcall("glEnableClientState(GL_NORMAL_ARRAY)");
5217 else
5219 gl_info->gl_ops.gl.p_glNormal3f(0, 0, 0);
5220 checkGLcall("glNormal3f(0, 0, 0)");
5223 /* Diffuse colour */
5224 if (si->use_map & (1u << WINED3D_FFP_DIFFUSE))
5226 e = &si->elements[WINED3D_FFP_DIFFUSE];
5227 format_gl = wined3d_format_gl(e->format);
5229 if (current_bo != e->data.buffer_object)
5231 GL_EXTCALL(glBindBuffer(GL_ARRAY_BUFFER, e->data.buffer_object));
5232 checkGLcall("glBindBuffer");
5233 current_bo = e->data.buffer_object;
5236 TRACE("glColorPointer(%#x, %#x %#x, %p);\n",
5237 format_gl->vtx_format, format_gl->vtx_type, e->stride,
5238 e->data.addr + state->load_base_vertex_index * e->stride);
5239 gl_info->gl_ops.gl.p_glColorPointer(format_gl->vtx_format, format_gl->vtx_type, e->stride,
5240 e->data.addr + state->load_base_vertex_index * e->stride);
5241 checkGLcall("glColorPointer(4, GL_UNSIGNED_BYTE, ...)");
5242 gl_info->gl_ops.gl.p_glEnableClientState(GL_COLOR_ARRAY);
5243 checkGLcall("glEnableClientState(GL_COLOR_ARRAY)");
5246 else
5248 gl_info->gl_ops.gl.p_glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
5249 checkGLcall("glColor4f(1, 1, 1, 1)");
5252 /* Specular colour */
5253 if (si->use_map & (1u << WINED3D_FFP_SPECULAR))
5255 TRACE("Setting specular colour.\n");
5257 e = &si->elements[WINED3D_FFP_SPECULAR];
5259 if (gl_info->supported[EXT_SECONDARY_COLOR])
5261 GLint format;
5262 GLenum type;
5264 format_gl = wined3d_format_gl(e->format);
5265 type = format_gl->vtx_type;
5266 format = format_gl->vtx_format;
5268 if (current_bo != e->data.buffer_object)
5270 GL_EXTCALL(glBindBuffer(GL_ARRAY_BUFFER, e->data.buffer_object));
5271 checkGLcall("glBindBuffer");
5272 current_bo = e->data.buffer_object;
5275 if (format != 4 || (gl_info->quirks & WINED3D_QUIRK_ALLOWS_SPECULAR_ALPHA))
5277 /* Usually specular colors only allow 3 components, since they have no alpha. In D3D, the specular alpha
5278 * contains the fog coordinate, which is passed to GL with GL_EXT_fog_coord. However, the fixed function
5279 * vertex pipeline can pass the specular alpha through, and pixel shaders can read it. So it GL accepts
5280 * 4 component secondary colors use it
5282 TRACE("glSecondaryColorPointer(%#x, %#x, %#x, %p);\n", format, type, e->stride,
5283 e->data.addr + state->load_base_vertex_index * e->stride);
5284 GL_EXTCALL(glSecondaryColorPointerEXT(format, type, e->stride,
5285 e->data.addr + state->load_base_vertex_index * e->stride));
5286 checkGLcall("glSecondaryColorPointerEXT(format, type, ...)");
5288 else
5290 switch (type)
5292 case GL_UNSIGNED_BYTE:
5293 TRACE("glSecondaryColorPointer(3, GL_UNSIGNED_BYTE, %#x, %p);\n", e->stride,
5294 e->data.addr + state->load_base_vertex_index * e->stride);
5295 GL_EXTCALL(glSecondaryColorPointerEXT(3, GL_UNSIGNED_BYTE, e->stride,
5296 e->data.addr + state->load_base_vertex_index * e->stride));
5297 checkGLcall("glSecondaryColorPointerEXT(3, GL_UNSIGNED_BYTE, ...)");
5298 break;
5300 default:
5301 FIXME("Add 4 component specular colour pointers for type %#x.\n", type);
5302 /* Make sure that the right colour component is dropped. */
5303 TRACE("glSecondaryColorPointer(3, %#x, %#x, %p);\n", type, e->stride,
5304 e->data.addr + state->load_base_vertex_index * e->stride);
5305 GL_EXTCALL(glSecondaryColorPointerEXT(3, type, e->stride,
5306 e->data.addr + state->load_base_vertex_index * e->stride));
5307 checkGLcall("glSecondaryColorPointerEXT(3, type, ...)");
5310 gl_info->gl_ops.gl.p_glEnableClientState(GL_SECONDARY_COLOR_ARRAY_EXT);
5311 checkGLcall("glEnableClientState(GL_SECONDARY_COLOR_ARRAY_EXT)");
5313 else
5315 WARN("Specular colour is not supported in this GL implementation.\n");
5318 else
5320 if (gl_info->supported[EXT_SECONDARY_COLOR])
5322 GL_EXTCALL(glSecondaryColor3fEXT)(0, 0, 0);
5323 checkGLcall("glSecondaryColor3fEXT(0, 0, 0)");
5325 else
5327 WARN("Specular colour is not supported in this GL implementation.\n");
5331 /* Texture coordinates */
5332 context_load_tex_coords(context, si, &current_bo, state);
5335 static void context_unload_numbered_array(struct wined3d_context *context, unsigned int i)
5337 const struct wined3d_gl_info *gl_info = context->gl_info;
5339 GL_EXTCALL(glDisableVertexAttribArray(i));
5340 checkGLcall("glDisableVertexAttribArray");
5341 if (gl_info->supported[ARB_INSTANCED_ARRAYS])
5342 GL_EXTCALL(glVertexAttribDivisor(i, 0));
5344 context->numbered_array_mask &= ~(1u << i);
5347 static void context_unload_numbered_arrays(struct wined3d_context *context)
5349 unsigned int i;
5351 while (context->numbered_array_mask)
5353 i = wined3d_bit_scan(&context->numbered_array_mask);
5354 context_unload_numbered_array(context, i);
5358 static void context_load_numbered_arrays(struct wined3d_context *context,
5359 const struct wined3d_stream_info *stream_info, const struct wined3d_state *state)
5361 const struct wined3d_shader *vs = state->shader[WINED3D_SHADER_TYPE_VERTEX];
5362 const struct wined3d_gl_info *gl_info = context->gl_info;
5363 GLuint current_bo;
5364 unsigned int i;
5366 /* Default to no instancing. */
5367 context->instance_count = 0;
5368 current_bo = gl_info->supported[ARB_VERTEX_BUFFER_OBJECT] ? ~0u : 0;
5370 for (i = 0; i < MAX_ATTRIBS; ++i)
5372 const struct wined3d_stream_info_element *element = &stream_info->elements[i];
5373 const struct wined3d_stream_state *stream;
5374 const struct wined3d_format_gl *format_gl;
5376 if (!(stream_info->use_map & (1u << i)))
5378 if (context->numbered_array_mask & (1u << i))
5379 context_unload_numbered_array(context, i);
5380 if (!use_vs(state) && i == WINED3D_FFP_DIFFUSE)
5381 GL_EXTCALL(glVertexAttrib4f(i, 1.0f, 1.0f, 1.0f, 1.0f));
5382 else
5383 GL_EXTCALL(glVertexAttrib4f(i, 0.0f, 0.0f, 0.0f, 0.0f));
5384 continue;
5387 format_gl = wined3d_format_gl(element->format);
5388 stream = &state->streams[element->stream_idx];
5390 if ((stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA) && !context->instance_count)
5391 context->instance_count = state->streams[0].frequency;
5393 if (gl_info->supported[ARB_INSTANCED_ARRAYS])
5395 GL_EXTCALL(glVertexAttribDivisor(i, element->divisor));
5397 else if (element->divisor)
5399 /* Unload instanced arrays, they will be loaded using immediate
5400 * mode instead. */
5401 if (context->numbered_array_mask & (1u << i))
5402 context_unload_numbered_array(context, i);
5403 continue;
5406 TRACE("Loading array %u %s.\n", i, debug_bo_address(&element->data));
5408 if (element->stride)
5410 DWORD format_flags = format_gl->f.flags[WINED3D_GL_RES_TYPE_BUFFER];
5412 if (current_bo != element->data.buffer_object)
5414 GL_EXTCALL(glBindBuffer(GL_ARRAY_BUFFER, element->data.buffer_object));
5415 checkGLcall("glBindBuffer");
5416 current_bo = element->data.buffer_object;
5418 /* Use the VBO to find out if a vertex buffer exists, not the vb
5419 * pointer. vb can point to a user pointer data blob. In that case
5420 * current_bo will be 0. If there is a vertex buffer but no vbo we
5421 * won't be load converted attributes anyway. */
5422 if (vs && vs->reg_maps.shader_version.major >= 4 && (format_flags & WINED3DFMT_FLAG_INTEGER))
5424 GL_EXTCALL(glVertexAttribIPointer(i, format_gl->vtx_format, format_gl->vtx_type,
5425 element->stride, element->data.addr + state->load_base_vertex_index * element->stride));
5427 else
5429 GL_EXTCALL(glVertexAttribPointer(i, format_gl->vtx_format, format_gl->vtx_type,
5430 !!(format_flags & WINED3DFMT_FLAG_NORMALISED), element->stride,
5431 element->data.addr + state->load_base_vertex_index * element->stride));
5434 if (!(context->numbered_array_mask & (1u << i)))
5436 GL_EXTCALL(glEnableVertexAttribArray(i));
5437 context->numbered_array_mask |= (1u << i);
5440 else
5442 /* Stride = 0 means always the same values.
5443 * glVertexAttribPointer() doesn't do that. Instead disable the
5444 * pointer and set up the attribute statically. But we have to
5445 * figure out the system memory address. */
5446 const BYTE *ptr = element->data.addr;
5447 if (element->data.buffer_object)
5448 ptr += (ULONG_PTR)wined3d_buffer_load_sysmem(stream->buffer, context);
5450 if (context->numbered_array_mask & (1u << i))
5451 context_unload_numbered_array(context, i);
5453 switch (format_gl->f.id)
5455 case WINED3DFMT_R32_FLOAT:
5456 GL_EXTCALL(glVertexAttrib1fv(i, (const GLfloat *)ptr));
5457 break;
5458 case WINED3DFMT_R32G32_FLOAT:
5459 GL_EXTCALL(glVertexAttrib2fv(i, (const GLfloat *)ptr));
5460 break;
5461 case WINED3DFMT_R32G32B32_FLOAT:
5462 GL_EXTCALL(glVertexAttrib3fv(i, (const GLfloat *)ptr));
5463 break;
5464 case WINED3DFMT_R32G32B32A32_FLOAT:
5465 GL_EXTCALL(glVertexAttrib4fv(i, (const GLfloat *)ptr));
5466 break;
5467 case WINED3DFMT_R8G8B8A8_UINT:
5468 GL_EXTCALL(glVertexAttrib4ubv(i, ptr));
5469 break;
5470 case WINED3DFMT_B8G8R8A8_UNORM:
5471 if (gl_info->supported[ARB_VERTEX_ARRAY_BGRA])
5473 const DWORD *src = (const DWORD *)ptr;
5474 DWORD c = *src & 0xff00ff00u;
5475 c |= (*src & 0xff0000u) >> 16;
5476 c |= (*src & 0xffu) << 16;
5477 GL_EXTCALL(glVertexAttrib4Nubv(i, (GLubyte *)&c));
5478 break;
5480 /* else fallthrough */
5481 case WINED3DFMT_R8G8B8A8_UNORM:
5482 GL_EXTCALL(glVertexAttrib4Nubv(i, ptr));
5483 break;
5484 case WINED3DFMT_R16G16_SINT:
5485 GL_EXTCALL(glVertexAttrib2sv(i, (const GLshort *)ptr));
5486 break;
5487 case WINED3DFMT_R16G16B16A16_SINT:
5488 GL_EXTCALL(glVertexAttrib4sv(i, (const GLshort *)ptr));
5489 break;
5490 case WINED3DFMT_R16G16_SNORM:
5492 const GLshort s[4] = {((const GLshort *)ptr)[0], ((const GLshort *)ptr)[1], 0, 1};
5493 GL_EXTCALL(glVertexAttrib4Nsv(i, s));
5494 break;
5496 case WINED3DFMT_R16G16_UNORM:
5498 const GLushort s[4] = {((const GLushort *)ptr)[0], ((const GLushort *)ptr)[1], 0, 1};
5499 GL_EXTCALL(glVertexAttrib4Nusv(i, s));
5500 break;
5502 case WINED3DFMT_R16G16B16A16_SNORM:
5503 GL_EXTCALL(glVertexAttrib4Nsv(i, (const GLshort *)ptr));
5504 break;
5505 case WINED3DFMT_R16G16B16A16_UNORM:
5506 GL_EXTCALL(glVertexAttrib4Nusv(i, (const GLushort *)ptr));
5507 break;
5508 case WINED3DFMT_R10G10B10X2_UINT:
5509 FIXME("Unsure about WINED3DDECLTYPE_UDEC3.\n");
5510 /*glVertexAttrib3usvARB(i, (const GLushort *)ptr); Does not exist */
5511 break;
5512 case WINED3DFMT_R10G10B10X2_SNORM:
5513 FIXME("Unsure about WINED3DDECLTYPE_DEC3N.\n");
5514 /*glVertexAttrib3NusvARB(i, (const GLushort *)ptr); Does not exist */
5515 break;
5516 case WINED3DFMT_R16G16_FLOAT:
5517 if (gl_info->supported[NV_HALF_FLOAT] && gl_info->supported[NV_VERTEX_PROGRAM])
5519 /* Not supported by GL_ARB_half_float_vertex. */
5520 GL_EXTCALL(glVertexAttrib2hvNV(i, (const GLhalfNV *)ptr));
5522 else
5524 float x = float_16_to_32(((const unsigned short *)ptr) + 0);
5525 float y = float_16_to_32(((const unsigned short *)ptr) + 1);
5526 GL_EXTCALL(glVertexAttrib2f(i, x, y));
5528 break;
5529 case WINED3DFMT_R16G16B16A16_FLOAT:
5530 if (gl_info->supported[NV_HALF_FLOAT] && gl_info->supported[NV_VERTEX_PROGRAM])
5532 /* Not supported by GL_ARB_half_float_vertex. */
5533 GL_EXTCALL(glVertexAttrib4hvNV(i, (const GLhalfNV *)ptr));
5535 else
5537 float x = float_16_to_32(((const unsigned short *)ptr) + 0);
5538 float y = float_16_to_32(((const unsigned short *)ptr) + 1);
5539 float z = float_16_to_32(((const unsigned short *)ptr) + 2);
5540 float w = float_16_to_32(((const unsigned short *)ptr) + 3);
5541 GL_EXTCALL(glVertexAttrib4f(i, x, y, z, w));
5543 break;
5544 default:
5545 ERR("Unexpected declaration in stride 0 attributes.\n");
5546 break;
5551 checkGLcall("Loading numbered arrays");
5554 void context_update_stream_sources(struct wined3d_context *context, const struct wined3d_state *state)
5557 if (context->use_immediate_mode_draw)
5558 return;
5560 context_unload_vertex_data(context);
5561 if (context->d3d_info->ffp_generic_attributes || use_vs(state))
5563 TRACE("Loading numbered arrays.\n");
5564 context_load_numbered_arrays(context, &context->stream_info, state);
5565 return;
5568 TRACE("Loading named arrays.\n");
5569 context_unload_numbered_arrays(context);
5570 context_load_vertex_data(context, &context->stream_info, state);
5571 context->namedArraysLoaded = TRUE;
5574 static void apply_texture_blit_state(const struct wined3d_gl_info *gl_info, struct gl_texture *texture,
5575 GLenum target, unsigned int level, enum wined3d_texture_filter_type filter)
5577 gl_info->gl_ops.gl.p_glTexParameteri(target, GL_TEXTURE_MAG_FILTER, wined3d_gl_mag_filter(filter));
5578 gl_info->gl_ops.gl.p_glTexParameteri(target, GL_TEXTURE_MIN_FILTER,
5579 wined3d_gl_min_mip_filter(filter, WINED3D_TEXF_NONE));
5580 gl_info->gl_ops.gl.p_glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
5581 gl_info->gl_ops.gl.p_glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
5582 if (gl_info->supported[EXT_TEXTURE_SRGB_DECODE])
5583 gl_info->gl_ops.gl.p_glTexParameteri(target, GL_TEXTURE_SRGB_DECODE_EXT, GL_SKIP_DECODE_EXT);
5584 gl_info->gl_ops.gl.p_glTexParameteri(target, GL_TEXTURE_BASE_LEVEL, level);
5586 /* We changed the filtering settings on the texture. Make sure they get
5587 * reset on subsequent draws. */
5588 texture->sampler_desc.mag_filter = WINED3D_TEXF_POINT;
5589 texture->sampler_desc.min_filter = WINED3D_TEXF_POINT;
5590 texture->sampler_desc.mip_filter = WINED3D_TEXF_NONE;
5591 texture->sampler_desc.address_u = WINED3D_TADDRESS_CLAMP;
5592 texture->sampler_desc.address_v = WINED3D_TADDRESS_CLAMP;
5593 texture->sampler_desc.srgb_decode = FALSE;
5594 texture->base_level = level;
5597 /* Context activation is done by the caller. */
5598 void context_draw_shaded_quad(struct wined3d_context *context, struct wined3d_texture_gl *texture_gl,
5599 unsigned int sub_resource_idx, const RECT *src_rect, const RECT *dst_rect,
5600 enum wined3d_texture_filter_type filter)
5602 const struct wined3d_gl_info *gl_info = context->gl_info;
5603 struct wined3d_blt_info info;
5604 unsigned int level, w, h, i;
5605 SIZE dst_size;
5606 struct blit_vertex
5608 float x, y;
5609 struct wined3d_vec3 texcoord;
5611 quad[4];
5613 texture2d_get_blt_info(texture_gl, sub_resource_idx, src_rect, &info);
5615 level = sub_resource_idx % texture_gl->t.level_count;
5616 context_bind_texture(context, info.bind_target, texture_gl->texture_rgb.name);
5617 apply_texture_blit_state(gl_info, &texture_gl->texture_rgb, info.bind_target, level, filter);
5618 gl_info->gl_ops.gl.p_glTexParameteri(info.bind_target, GL_TEXTURE_MAX_LEVEL, level);
5620 context_get_rt_size(context, &dst_size);
5621 w = dst_size.cx;
5622 h = dst_size.cy;
5624 quad[0].x = dst_rect->left * 2.0f / w - 1.0f;
5625 quad[0].y = dst_rect->top * 2.0f / h - 1.0f;
5626 quad[0].texcoord = info.texcoords[0];
5628 quad[1].x = dst_rect->right * 2.0f / w - 1.0f;
5629 quad[1].y = dst_rect->top * 2.0f / h - 1.0f;
5630 quad[1].texcoord = info.texcoords[1];
5632 quad[2].x = dst_rect->left * 2.0f / w - 1.0f;
5633 quad[2].y = dst_rect->bottom * 2.0f / h - 1.0f;
5634 quad[2].texcoord = info.texcoords[2];
5636 quad[3].x = dst_rect->right * 2.0f / w - 1.0f;
5637 quad[3].y = dst_rect->bottom * 2.0f / h - 1.0f;
5638 quad[3].texcoord = info.texcoords[3];
5640 /* Draw a quad. */
5641 if (gl_info->supported[ARB_VERTEX_BUFFER_OBJECT])
5643 if (!context->blit_vbo)
5644 GL_EXTCALL(glGenBuffers(1, &context->blit_vbo));
5645 GL_EXTCALL(glBindBuffer(GL_ARRAY_BUFFER, context->blit_vbo));
5647 context_unload_vertex_data(context);
5648 context_unload_numbered_arrays(context);
5650 GL_EXTCALL(glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STREAM_DRAW));
5651 GL_EXTCALL(glVertexAttribPointer(0, 2, GL_FLOAT, FALSE, sizeof(*quad), NULL));
5652 GL_EXTCALL(glVertexAttribPointer(1, 3, GL_FLOAT, FALSE, sizeof(*quad),
5653 (void *)FIELD_OFFSET(struct blit_vertex, texcoord)));
5655 GL_EXTCALL(glEnableVertexAttribArray(0));
5656 GL_EXTCALL(glEnableVertexAttribArray(1));
5658 gl_info->gl_ops.gl.p_glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
5660 GL_EXTCALL(glBindBuffer(GL_ARRAY_BUFFER, 0));
5661 GL_EXTCALL(glDisableVertexAttribArray(1));
5662 GL_EXTCALL(glDisableVertexAttribArray(0));
5664 else
5666 gl_info->gl_ops.gl.p_glBegin(GL_TRIANGLE_STRIP);
5668 for (i = 0; i < ARRAY_SIZE(quad); ++i)
5670 GL_EXTCALL(glVertexAttrib3fv(1, &quad[i].texcoord.x));
5671 GL_EXTCALL(glVertexAttrib2fv(0, &quad[i].x));
5674 gl_info->gl_ops.gl.p_glEnd();
5676 checkGLcall("draw");
5678 gl_info->gl_ops.gl.p_glTexParameteri(info.bind_target, GL_TEXTURE_MAX_LEVEL, texture_gl->t.level_count - 1);
5679 context_bind_texture(context, info.bind_target, 0);
5682 /* Context activation is done by the caller. */
5683 void context_draw_textured_quad(struct wined3d_context *context, struct wined3d_texture_gl *texture_gl,
5684 unsigned int sub_resource_idx, const RECT *src_rect, const RECT *dst_rect,
5685 enum wined3d_texture_filter_type filter)
5687 const struct wined3d_gl_info *gl_info = context->gl_info;
5688 struct wined3d_blt_info info;
5689 unsigned int level;
5691 texture2d_get_blt_info(texture_gl, sub_resource_idx, src_rect, &info);
5693 gl_info->gl_ops.gl.p_glEnable(info.bind_target);
5694 checkGLcall("glEnable(bind_target)");
5696 level = sub_resource_idx % texture_gl->t.level_count;
5697 context_bind_texture(context, info.bind_target, texture_gl->texture_rgb.name);
5698 apply_texture_blit_state(gl_info, &texture_gl->texture_rgb, info.bind_target, level, filter);
5699 gl_info->gl_ops.gl.p_glTexParameteri(info.bind_target, GL_TEXTURE_MAX_LEVEL, level);
5700 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
5701 checkGLcall("glTexEnvi");
5703 /* Draw a quad. */
5704 gl_info->gl_ops.gl.p_glBegin(GL_TRIANGLE_STRIP);
5705 gl_info->gl_ops.gl.p_glTexCoord3fv(&info.texcoords[0].x);
5706 gl_info->gl_ops.gl.p_glVertex2i(dst_rect->left, dst_rect->top);
5708 gl_info->gl_ops.gl.p_glTexCoord3fv(&info.texcoords[1].x);
5709 gl_info->gl_ops.gl.p_glVertex2i(dst_rect->right, dst_rect->top);
5711 gl_info->gl_ops.gl.p_glTexCoord3fv(&info.texcoords[2].x);
5712 gl_info->gl_ops.gl.p_glVertex2i(dst_rect->left, dst_rect->bottom);
5714 gl_info->gl_ops.gl.p_glTexCoord3fv(&info.texcoords[3].x);
5715 gl_info->gl_ops.gl.p_glVertex2i(dst_rect->right, dst_rect->bottom);
5716 gl_info->gl_ops.gl.p_glEnd();
5718 gl_info->gl_ops.gl.p_glTexParameteri(info.bind_target, GL_TEXTURE_MAX_LEVEL, texture_gl->t.level_count - 1);
5719 context_bind_texture(context, info.bind_target, 0);