2 * Context and render target management in wined3d
4 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
5 * Copyright 2009 Henri Verbeet for CodeWeavers
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 #include "wined3d_private.h"
29 WINE_DEFAULT_DEBUG_CHANNEL(d3d
);
31 #define GLINFO_LOCATION (*gl_info)
33 static DWORD wined3d_context_tls_idx
;
35 /* FBO helper functions */
37 /* GL locking is done by the caller */
38 void context_bind_fbo(struct WineD3DContext
*context
, GLenum target
, GLuint
*fbo
)
40 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
51 GL_EXTCALL(glGenFramebuffersEXT(1, fbo
));
52 checkGLcall("glGenFramebuffersEXT()");
53 TRACE("Created FBO %u.\n", *fbo
);
60 case GL_READ_FRAMEBUFFER_EXT
:
61 if (context
->fbo_read_binding
== f
) return;
62 context
->fbo_read_binding
= f
;
65 case GL_DRAW_FRAMEBUFFER_EXT
:
66 if (context
->fbo_draw_binding
== f
) return;
67 context
->fbo_draw_binding
= f
;
70 case GL_FRAMEBUFFER_EXT
:
71 if (context
->fbo_read_binding
== f
72 && context
->fbo_draw_binding
== f
) return;
73 context
->fbo_read_binding
= f
;
74 context
->fbo_draw_binding
= f
;
78 FIXME("Unhandled target %#x.\n", target
);
82 GL_EXTCALL(glBindFramebufferEXT(target
, f
));
83 checkGLcall("glBindFramebuffer()");
86 /* GL locking is done by the caller */
87 static void context_clean_fbo_attachments(const struct wined3d_gl_info
*gl_info
)
91 for (i
= 0; i
< GL_LIMITS(buffers
); ++i
)
93 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT
, GL_COLOR_ATTACHMENT0_EXT
+ i
, GL_TEXTURE_2D
, 0, 0));
94 checkGLcall("glFramebufferTexture2D()");
96 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT
, GL_DEPTH_ATTACHMENT_EXT
, GL_TEXTURE_2D
, 0, 0));
97 checkGLcall("glFramebufferTexture2D()");
99 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT
, GL_STENCIL_ATTACHMENT_EXT
, GL_TEXTURE_2D
, 0, 0));
100 checkGLcall("glFramebufferTexture2D()");
103 /* GL locking is done by the caller */
104 static void context_destroy_fbo(struct WineD3DContext
*context
, GLuint
*fbo
)
106 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
108 context_bind_fbo(context
, GL_FRAMEBUFFER_EXT
, fbo
);
109 context_clean_fbo_attachments(gl_info
);
110 context_bind_fbo(context
, GL_FRAMEBUFFER_EXT
, NULL
);
112 GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo
));
113 checkGLcall("glDeleteFramebuffers()");
116 /* GL locking is done by the caller */
117 static void context_apply_attachment_filter_states(IWineD3DSurface
*surface
, BOOL force_preload
)
119 const IWineD3DSurfaceImpl
*surface_impl
= (IWineD3DSurfaceImpl
*)surface
;
120 IWineD3DDeviceImpl
*device
= surface_impl
->resource
.wineD3DDevice
;
121 IWineD3DBaseTextureImpl
*texture_impl
;
122 BOOL update_minfilter
= FALSE
;
123 BOOL update_magfilter
= FALSE
;
125 /* Update base texture states array */
126 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface
, &IID_IWineD3DBaseTexture
, (void **)&texture_impl
)))
128 if (texture_impl
->baseTexture
.states
[WINED3DTEXSTA_MINFILTER
] != WINED3DTEXF_POINT
129 || texture_impl
->baseTexture
.states
[WINED3DTEXSTA_MIPFILTER
] != WINED3DTEXF_NONE
)
131 texture_impl
->baseTexture
.states
[WINED3DTEXSTA_MINFILTER
] = WINED3DTEXF_POINT
;
132 texture_impl
->baseTexture
.states
[WINED3DTEXSTA_MIPFILTER
] = WINED3DTEXF_NONE
;
133 update_minfilter
= TRUE
;
136 if (texture_impl
->baseTexture
.states
[WINED3DTEXSTA_MAGFILTER
] != WINED3DTEXF_POINT
)
138 texture_impl
->baseTexture
.states
[WINED3DTEXSTA_MAGFILTER
] = WINED3DTEXF_POINT
;
139 update_magfilter
= TRUE
;
142 if (texture_impl
->baseTexture
.bindCount
)
144 WARN("Render targets should not be bound to a sampler\n");
145 IWineD3DDeviceImpl_MarkStateDirty(device
, STATE_SAMPLER(texture_impl
->baseTexture
.sampler
));
148 IWineD3DBaseTexture_Release((IWineD3DBaseTexture
*)texture_impl
);
151 if (update_minfilter
|| update_magfilter
|| force_preload
)
153 GLenum target
, bind_target
;
156 target
= surface_impl
->texture_target
;
157 if (target
== GL_TEXTURE_2D
)
159 bind_target
= GL_TEXTURE_2D
;
160 glGetIntegerv(GL_TEXTURE_BINDING_2D
, &old_binding
);
161 } else if (target
== GL_TEXTURE_RECTANGLE_ARB
) {
162 bind_target
= GL_TEXTURE_RECTANGLE_ARB
;
163 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB
, &old_binding
);
165 bind_target
= GL_TEXTURE_CUBE_MAP_ARB
;
166 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB
, &old_binding
);
169 surface_internal_preload(surface
, SRGB_RGB
);
171 glBindTexture(bind_target
, surface_impl
->texture_name
);
172 if (update_minfilter
) glTexParameteri(bind_target
, GL_TEXTURE_MIN_FILTER
, GL_NEAREST
);
173 if (update_magfilter
) glTexParameteri(bind_target
, GL_TEXTURE_MAG_FILTER
, GL_NEAREST
);
174 glBindTexture(bind_target
, old_binding
);
177 checkGLcall("apply_attachment_filter_states()");
180 /* GL locking is done by the caller */
181 void context_attach_depth_stencil_fbo(struct WineD3DContext
*context
,
182 GLenum fbo_target
, IWineD3DSurface
*depth_stencil
, BOOL use_render_buffer
)
184 IWineD3DSurfaceImpl
*depth_stencil_impl
= (IWineD3DSurfaceImpl
*)depth_stencil
;
185 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
187 TRACE("Attach depth stencil %p\n", depth_stencil
);
191 DWORD format_flags
= depth_stencil_impl
->resource
.format_desc
->Flags
;
193 if (use_render_buffer
&& depth_stencil_impl
->current_renderbuffer
)
195 if (format_flags
& WINED3DFMT_FLAG_DEPTH
)
197 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target
, GL_DEPTH_ATTACHMENT_EXT
,
198 GL_RENDERBUFFER_EXT
, depth_stencil_impl
->current_renderbuffer
->id
));
199 checkGLcall("glFramebufferRenderbufferEXT()");
202 if (format_flags
& WINED3DFMT_FLAG_STENCIL
)
204 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target
, GL_STENCIL_ATTACHMENT_EXT
,
205 GL_RENDERBUFFER_EXT
, depth_stencil_impl
->current_renderbuffer
->id
));
206 checkGLcall("glFramebufferRenderbufferEXT()");
211 context_apply_attachment_filter_states(depth_stencil
, TRUE
);
213 if (format_flags
& WINED3DFMT_FLAG_DEPTH
)
215 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target
, GL_DEPTH_ATTACHMENT_EXT
,
216 depth_stencil_impl
->texture_target
, depth_stencil_impl
->texture_name
,
217 depth_stencil_impl
->texture_level
));
218 checkGLcall("glFramebufferTexture2DEXT()");
221 if (format_flags
& WINED3DFMT_FLAG_STENCIL
)
223 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target
, GL_STENCIL_ATTACHMENT_EXT
,
224 depth_stencil_impl
->texture_target
, depth_stencil_impl
->texture_name
,
225 depth_stencil_impl
->texture_level
));
226 checkGLcall("glFramebufferTexture2DEXT()");
230 if (!(format_flags
& WINED3DFMT_FLAG_DEPTH
))
232 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target
, GL_DEPTH_ATTACHMENT_EXT
, GL_TEXTURE_2D
, 0, 0));
233 checkGLcall("glFramebufferTexture2DEXT()");
236 if (!(format_flags
& WINED3DFMT_FLAG_STENCIL
))
238 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target
, GL_STENCIL_ATTACHMENT_EXT
, GL_TEXTURE_2D
, 0, 0));
239 checkGLcall("glFramebufferTexture2DEXT()");
244 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target
, GL_DEPTH_ATTACHMENT_EXT
, GL_TEXTURE_2D
, 0, 0));
245 checkGLcall("glFramebufferTexture2DEXT()");
247 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target
, GL_STENCIL_ATTACHMENT_EXT
, GL_TEXTURE_2D
, 0, 0));
248 checkGLcall("glFramebufferTexture2DEXT()");
252 /* GL locking is done by the caller */
253 void context_attach_surface_fbo(const struct WineD3DContext
*context
,
254 GLenum fbo_target
, DWORD idx
, IWineD3DSurface
*surface
)
256 const IWineD3DSurfaceImpl
*surface_impl
= (IWineD3DSurfaceImpl
*)surface
;
257 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
259 TRACE("Attach surface %p to %u\n", surface
, idx
);
263 context_apply_attachment_filter_states(surface
, TRUE
);
265 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target
, GL_COLOR_ATTACHMENT0_EXT
+ idx
, surface_impl
->texture_target
,
266 surface_impl
->texture_name
, surface_impl
->texture_level
));
267 checkGLcall("glFramebufferTexture2DEXT()");
269 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target
, GL_COLOR_ATTACHMENT0_EXT
+ idx
, GL_TEXTURE_2D
, 0, 0));
270 checkGLcall("glFramebufferTexture2DEXT()");
274 /* GL locking is done by the caller */
275 static void context_check_fbo_status(struct WineD3DContext
*context
)
277 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
280 status
= GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT
));
281 if (status
== GL_FRAMEBUFFER_COMPLETE_EXT
)
283 TRACE("FBO complete\n");
285 IWineD3DSurfaceImpl
*attachment
;
287 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status
), status
);
289 /* Dump the FBO attachments */
290 for (i
= 0; i
< GL_LIMITS(buffers
); ++i
)
292 attachment
= (IWineD3DSurfaceImpl
*)context
->current_fbo
->render_targets
[i
];
295 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
296 i
, attachment
, debug_d3dformat(attachment
->resource
.format_desc
->format
),
297 attachment
->pow2Width
, attachment
->pow2Height
);
300 attachment
= (IWineD3DSurfaceImpl
*)context
->current_fbo
->depth_stencil
;
303 FIXME("\tDepth attachment: (%p) %s %ux%u\n",
304 attachment
, debug_d3dformat(attachment
->resource
.format_desc
->format
),
305 attachment
->pow2Width
, attachment
->pow2Height
);
310 static struct fbo_entry
*context_create_fbo_entry(struct WineD3DContext
*context
)
312 IWineD3DDeviceImpl
*device
= ((IWineD3DSurfaceImpl
*)context
->surface
)->resource
.wineD3DDevice
;
313 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
314 struct fbo_entry
*entry
;
316 entry
= HeapAlloc(GetProcessHeap(), 0, sizeof(*entry
));
317 entry
->render_targets
= HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers
) * sizeof(*entry
->render_targets
));
318 memcpy(entry
->render_targets
, device
->render_targets
, GL_LIMITS(buffers
) * sizeof(*entry
->render_targets
));
319 entry
->depth_stencil
= device
->stencilBufferTarget
;
320 entry
->attached
= FALSE
;
326 /* GL locking is done by the caller */
327 static void context_reuse_fbo_entry(struct WineD3DContext
*context
, struct fbo_entry
*entry
)
329 IWineD3DDeviceImpl
*device
= ((IWineD3DSurfaceImpl
*)context
->surface
)->resource
.wineD3DDevice
;
330 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
332 context_bind_fbo(context
, GL_FRAMEBUFFER_EXT
, &entry
->id
);
333 context_clean_fbo_attachments(gl_info
);
335 memcpy(entry
->render_targets
, device
->render_targets
, GL_LIMITS(buffers
) * sizeof(*entry
->render_targets
));
336 entry
->depth_stencil
= device
->stencilBufferTarget
;
337 entry
->attached
= FALSE
;
340 /* GL locking is done by the caller */
341 static void context_destroy_fbo_entry(struct WineD3DContext
*context
, struct fbo_entry
*entry
)
345 TRACE("Destroy FBO %d\n", entry
->id
);
346 context_destroy_fbo(context
, &entry
->id
);
348 --context
->fbo_entry_count
;
349 list_remove(&entry
->entry
);
350 HeapFree(GetProcessHeap(), 0, entry
->render_targets
);
351 HeapFree(GetProcessHeap(), 0, entry
);
355 /* GL locking is done by the caller */
356 static struct fbo_entry
*context_find_fbo_entry(struct WineD3DContext
*context
)
358 IWineD3DDeviceImpl
*device
= ((IWineD3DSurfaceImpl
*)context
->surface
)->resource
.wineD3DDevice
;
359 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
360 struct fbo_entry
*entry
;
362 LIST_FOR_EACH_ENTRY(entry
, &context
->fbo_list
, struct fbo_entry
, entry
)
364 if (!memcmp(entry
->render_targets
, device
->render_targets
, GL_LIMITS(buffers
) * sizeof(*entry
->render_targets
))
365 && entry
->depth_stencil
== device
->stencilBufferTarget
)
367 list_remove(&entry
->entry
);
368 list_add_head(&context
->fbo_list
, &entry
->entry
);
373 if (context
->fbo_entry_count
< WINED3D_MAX_FBO_ENTRIES
)
375 entry
= context_create_fbo_entry(context
);
376 list_add_head(&context
->fbo_list
, &entry
->entry
);
377 ++context
->fbo_entry_count
;
381 entry
= LIST_ENTRY(list_tail(&context
->fbo_list
), struct fbo_entry
, entry
);
382 context_reuse_fbo_entry(context
, entry
);
383 list_remove(&entry
->entry
);
384 list_add_head(&context
->fbo_list
, &entry
->entry
);
390 /* GL locking is done by the caller */
391 static void context_apply_fbo_entry(struct WineD3DContext
*context
, struct fbo_entry
*entry
)
393 IWineD3DDeviceImpl
*device
= ((IWineD3DSurfaceImpl
*)context
->surface
)->resource
.wineD3DDevice
;
394 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
397 context_bind_fbo(context
, GL_FRAMEBUFFER_EXT
, &entry
->id
);
399 if (!entry
->attached
)
401 /* Apply render targets */
402 for (i
= 0; i
< GL_LIMITS(buffers
); ++i
)
404 IWineD3DSurface
*render_target
= device
->render_targets
[i
];
405 context_attach_surface_fbo(context
, GL_FRAMEBUFFER_EXT
, i
, render_target
);
408 /* Apply depth targets */
409 if (device
->stencilBufferTarget
)
411 unsigned int w
= ((IWineD3DSurfaceImpl
*)device
->render_targets
[0])->pow2Width
;
412 unsigned int h
= ((IWineD3DSurfaceImpl
*)device
->render_targets
[0])->pow2Height
;
414 surface_set_compatible_renderbuffer(device
->stencilBufferTarget
, w
, h
);
416 context_attach_depth_stencil_fbo(context
, GL_FRAMEBUFFER_EXT
, device
->stencilBufferTarget
, TRUE
);
418 entry
->attached
= TRUE
;
420 for (i
= 0; i
< GL_LIMITS(buffers
); ++i
)
422 if (device
->render_targets
[i
])
423 context_apply_attachment_filter_states(device
->render_targets
[i
], FALSE
);
425 if (device
->stencilBufferTarget
)
426 context_apply_attachment_filter_states(device
->stencilBufferTarget
, FALSE
);
429 for (i
= 0; i
< GL_LIMITS(buffers
); ++i
)
431 if (device
->render_targets
[i
])
432 device
->draw_buffers
[i
] = GL_COLOR_ATTACHMENT0_EXT
+ i
;
434 device
->draw_buffers
[i
] = GL_NONE
;
438 /* GL locking is done by the caller */
439 static void context_apply_fbo_state(struct WineD3DContext
*context
)
441 IWineD3DDeviceImpl
*device
= ((IWineD3DSurfaceImpl
*)context
->surface
)->resource
.wineD3DDevice
;
443 if (device
->render_offscreen
)
445 context
->current_fbo
= context_find_fbo_entry(context
);
446 context_apply_fbo_entry(context
, context
->current_fbo
);
448 context
->current_fbo
= NULL
;
449 context_bind_fbo(context
, GL_FRAMEBUFFER_EXT
, NULL
);
452 context_check_fbo_status(context
);
455 /* Context activation is done by the caller. */
456 void context_alloc_occlusion_query(struct WineD3DContext
*context
, struct wined3d_occlusion_query
*query
)
458 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
460 if (context
->free_occlusion_query_count
)
462 query
->id
= context
->free_occlusion_queries
[--context
->free_occlusion_query_count
];
466 if (GL_SUPPORT(ARB_OCCLUSION_QUERY
))
469 GL_EXTCALL(glGenQueriesARB(1, &query
->id
));
470 checkGLcall("glGenQueriesARB");
473 TRACE("Allocated occlusion query %u in context %p.\n", query
->id
, context
);
477 WARN("Occlusion queries not supported, not allocating query id.\n");
482 query
->context
= context
;
483 list_add_head(&context
->occlusion_queries
, &query
->entry
);
486 void context_free_occlusion_query(struct wined3d_occlusion_query
*query
)
488 struct WineD3DContext
*context
= query
->context
;
490 list_remove(&query
->entry
);
491 query
->context
= NULL
;
493 if (context
->free_occlusion_query_count
>= context
->free_occlusion_query_size
- 1)
495 UINT new_size
= context
->free_occlusion_query_size
<< 1;
496 GLuint
*new_data
= HeapReAlloc(GetProcessHeap(), 0, context
->free_occlusion_queries
,
497 new_size
* sizeof(*context
->free_occlusion_queries
));
501 ERR("Failed to grow free list, leaking query %u in context %p.\n", query
->id
, context
);
505 context
->free_occlusion_query_size
= new_size
;
506 context
->free_occlusion_queries
= new_data
;
509 context
->free_occlusion_queries
[context
->free_occlusion_query_count
++] = query
->id
;
512 /* Context activation is done by the caller. */
513 void context_alloc_event_query(struct WineD3DContext
*context
, struct wined3d_event_query
*query
)
515 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
517 if (context
->free_event_query_count
)
519 query
->id
= context
->free_event_queries
[--context
->free_event_query_count
];
523 if (GL_SUPPORT(APPLE_FENCE
))
526 GL_EXTCALL(glGenFencesAPPLE(1, &query
->id
));
527 checkGLcall("glGenFencesAPPLE");
530 TRACE("Allocated event query %u in context %p.\n", query
->id
, context
);
532 else if(GL_SUPPORT(NV_FENCE
))
535 GL_EXTCALL(glGenFencesNV(1, &query
->id
));
536 checkGLcall("glGenFencesNV");
539 TRACE("Allocated event query %u in context %p.\n", query
->id
, context
);
543 WARN("Event queries not supported, not allocating query id.\n");
548 query
->context
= context
;
549 list_add_head(&context
->event_queries
, &query
->entry
);
552 void context_free_event_query(struct wined3d_event_query
*query
)
554 struct WineD3DContext
*context
= query
->context
;
556 list_remove(&query
->entry
);
557 query
->context
= NULL
;
559 if (context
->free_event_query_count
>= context
->free_event_query_size
- 1)
561 UINT new_size
= context
->free_event_query_size
<< 1;
562 GLuint
*new_data
= HeapReAlloc(GetProcessHeap(), 0, context
->free_event_queries
,
563 new_size
* sizeof(*context
->free_event_queries
));
567 ERR("Failed to grow free list, leaking query %u in context %p.\n", query
->id
, context
);
571 context
->free_event_query_size
= new_size
;
572 context
->free_event_queries
= new_data
;
575 context
->free_event_queries
[context
->free_event_query_count
++] = query
->id
;
578 void context_resource_released(IWineD3DDevice
*iface
, IWineD3DResource
*resource
, WINED3DRESOURCETYPE type
)
580 IWineD3DDeviceImpl
*This
= (IWineD3DDeviceImpl
*)iface
;
583 if (!This
->d3d_initialized
) return;
587 case WINED3DRTYPE_SURFACE
:
589 ActivateContext(This
, NULL
, CTXUSAGE_RESOURCELOAD
);
591 for (i
= 0; i
< This
->numContexts
; ++i
)
593 WineD3DContext
*context
= This
->contexts
[i
];
594 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
595 struct fbo_entry
*entry
, *entry2
;
599 LIST_FOR_EACH_ENTRY_SAFE(entry
, entry2
, &context
->fbo_list
, struct fbo_entry
, entry
)
601 BOOL destroyed
= FALSE
;
604 for (j
= 0; !destroyed
&& j
< GL_LIMITS(buffers
); ++j
)
606 if (entry
->render_targets
[j
] == (IWineD3DSurface
*)resource
)
608 context_destroy_fbo_entry(context
, entry
);
613 if (!destroyed
&& entry
->depth_stencil
== (IWineD3DSurface
*)resource
)
614 context_destroy_fbo_entry(context
, entry
);
628 static void context_destroy_gl_resources(struct WineD3DContext
*context
)
630 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
631 struct wined3d_occlusion_query
*occlusion_query
;
632 struct wined3d_event_query
*event_query
;
633 struct fbo_entry
*entry
, *entry2
;
636 has_glctx
= pwglMakeCurrent(context
->hdc
, context
->glCtx
);
637 if (!has_glctx
) WARN("Failed to activate context. Window already destroyed?\n");
641 LIST_FOR_EACH_ENTRY(occlusion_query
, &context
->occlusion_queries
, struct wined3d_occlusion_query
, entry
)
643 if (has_glctx
&& GL_SUPPORT(ARB_OCCLUSION_QUERY
)) GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query
->id
));
644 occlusion_query
->context
= NULL
;
647 LIST_FOR_EACH_ENTRY(event_query
, &context
->event_queries
, struct wined3d_event_query
, entry
)
651 if (GL_SUPPORT(APPLE_FENCE
)) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query
->id
));
652 else if (GL_SUPPORT(NV_FENCE
)) GL_EXTCALL(glDeleteFencesNV(1, &event_query
->id
));
654 event_query
->context
= NULL
;
657 LIST_FOR_EACH_ENTRY_SAFE(entry
, entry2
, &context
->fbo_list
, struct fbo_entry
, entry
) {
658 if (!has_glctx
) entry
->id
= 0;
659 context_destroy_fbo_entry(context
, entry
);
663 if (context
->src_fbo
)
665 TRACE("Destroy src FBO %d\n", context
->src_fbo
);
666 context_destroy_fbo(context
, &context
->src_fbo
);
668 if (context
->dst_fbo
)
670 TRACE("Destroy dst FBO %d\n", context
->dst_fbo
);
671 context_destroy_fbo(context
, &context
->dst_fbo
);
673 if (context
->dummy_arbfp_prog
)
675 GL_EXTCALL(glDeleteProgramsARB(1, &context
->dummy_arbfp_prog
));
678 GL_EXTCALL(glDeleteQueriesARB(context
->free_occlusion_query_count
, context
->free_occlusion_queries
));
680 if (GL_SUPPORT(APPLE_FENCE
))
681 GL_EXTCALL(glDeleteFencesAPPLE(context
->free_event_query_count
, context
->free_event_queries
));
682 else if (GL_SUPPORT(NV_FENCE
))
683 GL_EXTCALL(glDeleteFencesNV(context
->free_event_query_count
, context
->free_event_queries
));
685 checkGLcall("context cleanup");
690 HeapFree(GetProcessHeap(), 0, context
->free_occlusion_queries
);
691 HeapFree(GetProcessHeap(), 0, context
->free_event_queries
);
693 if (!pwglMakeCurrent(NULL
, NULL
))
695 ERR("Failed to disable GL context.\n");
698 if (context
->isPBuffer
)
700 GL_EXTCALL(wglReleasePbufferDCARB(context
->pbuffer
, context
->hdc
));
701 GL_EXTCALL(wglDestroyPbufferARB(context
->pbuffer
));
705 ReleaseDC(context
->win_handle
, context
->hdc
);
708 pwglDeleteContext(context
->glCtx
);
711 DWORD
context_get_tls_idx(void)
713 return wined3d_context_tls_idx
;
716 void context_set_tls_idx(DWORD idx
)
718 wined3d_context_tls_idx
= idx
;
721 struct WineD3DContext
*context_get_current(void)
723 return TlsGetValue(wined3d_context_tls_idx
);
726 BOOL
context_set_current(struct WineD3DContext
*ctx
)
728 struct WineD3DContext
*old
= context_get_current();
732 TRACE("Already using D3D context %p.\n", ctx
);
740 TRACE("Switching away from destroyed context %p.\n", old
);
741 context_destroy_gl_resources(old
);
742 HeapFree(GetProcessHeap(), 0, old
);
752 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx
, ctx
->glCtx
, ctx
->hdc
);
753 if (!pwglMakeCurrent(ctx
->hdc
, ctx
->glCtx
))
755 ERR("Failed to make GL context %p current on device context %p.\n", ctx
->glCtx
, ctx
->hdc
);
762 TRACE("Clearing current D3D context.\n");
763 if (!pwglMakeCurrent(NULL
, NULL
))
765 ERR("Failed to clear current GL context.\n");
770 return TlsSetValue(wined3d_context_tls_idx
, ctx
);
773 /*****************************************************************************
774 * Context_MarkStateDirty
776 * Marks a state in a context dirty. Only one context, opposed to
777 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
781 * context: Context to mark the state dirty in
782 * state: State to mark dirty
783 * StateTable: Pointer to the state table in use(for state grouping)
785 *****************************************************************************/
786 static void Context_MarkStateDirty(WineD3DContext
*context
, DWORD state
, const struct StateEntry
*StateTable
) {
787 DWORD rep
= StateTable
[state
].representative
;
791 if(!rep
|| isStateDirty(context
, rep
)) return;
793 context
->dirtyArray
[context
->numDirtyEntries
++] = rep
;
796 context
->isStateDirty
[idx
] |= (1 << shift
);
799 /*****************************************************************************
802 * Adds a context to the context array. Helper function for CreateContext
804 * This method is not called in performance-critical code paths, only when a
805 * new render target or swapchain is created. Thus performance is not an issue
809 * This: Device to add the context for
810 * hdc: device context
811 * glCtx: WGL context to add
812 * pbuffer: optional pbuffer used with this context
814 *****************************************************************************/
815 static WineD3DContext
*AddContextToArray(IWineD3DDeviceImpl
*This
, HWND win_handle
, HDC hdc
, HGLRC glCtx
, HPBUFFERARB pbuffer
) {
816 WineD3DContext
**oldArray
= This
->contexts
;
819 This
->contexts
= HeapAlloc(GetProcessHeap(), 0, sizeof(*This
->contexts
) * (This
->numContexts
+ 1));
820 if(This
->contexts
== NULL
) {
821 ERR("Unable to grow the context array\n");
822 This
->contexts
= oldArray
;
826 memcpy(This
->contexts
, oldArray
, sizeof(*This
->contexts
) * This
->numContexts
);
829 This
->contexts
[This
->numContexts
] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(WineD3DContext
));
830 if(This
->contexts
[This
->numContexts
] == NULL
) {
831 ERR("Unable to allocate a new context\n");
832 HeapFree(GetProcessHeap(), 0, This
->contexts
);
833 This
->contexts
= oldArray
;
837 This
->contexts
[This
->numContexts
]->hdc
= hdc
;
838 This
->contexts
[This
->numContexts
]->glCtx
= glCtx
;
839 This
->contexts
[This
->numContexts
]->pbuffer
= pbuffer
;
840 This
->contexts
[This
->numContexts
]->win_handle
= win_handle
;
841 HeapFree(GetProcessHeap(), 0, oldArray
);
843 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
845 for(state
= 0; state
<= STATE_HIGHEST
; state
++) {
846 Context_MarkStateDirty(This
->contexts
[This
->numContexts
], state
, This
->StateTable
);
850 TRACE("Created context %p\n", This
->contexts
[This
->numContexts
- 1]);
851 return This
->contexts
[This
->numContexts
- 1];
854 /* This function takes care of WineD3D pixel format selection. */
855 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl
*This
, HDC hdc
,
856 const struct GlPixelFormatDesc
*color_format_desc
, const struct GlPixelFormatDesc
*ds_format_desc
,
857 BOOL auxBuffers
, int numSamples
, BOOL pbuffer
, BOOL findCompatible
)
860 unsigned int matchtry
;
861 short redBits
, greenBits
, blueBits
, alphaBits
, colorBits
;
862 short depthBits
=0, stencilBits
=0;
869 /* First, try without alpha match buffers. MacOS supports aux buffers only
870 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
871 * Then try without aux buffers - this is the most common cause for not
872 * finding a pixel format. Also some drivers(the open source ones)
873 * only offer 32 bit ARB pixel formats. First try without an exact alpha
874 * match, then try without an exact alpha and color match.
876 { TRUE
, TRUE
, TRUE
},
877 { TRUE
, FALSE
, TRUE
},
878 { FALSE
, TRUE
, TRUE
},
879 { FALSE
, FALSE
, TRUE
},
880 { TRUE
, FALSE
, FALSE
},
881 { FALSE
, FALSE
, FALSE
},
885 int nCfgs
= This
->adapter
->nCfgs
;
887 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
888 debug_d3dformat(color_format_desc
->format
), debug_d3dformat(ds_format_desc
->format
),
889 auxBuffers
, numSamples
, pbuffer
, findCompatible
);
891 if (!getColorBits(color_format_desc
, &redBits
, &greenBits
, &blueBits
, &alphaBits
, &colorBits
))
893 ERR("Unable to get color bits for format %s (%#x)!\n",
894 debug_d3dformat(color_format_desc
->format
), color_format_desc
->format
);
898 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
899 * You are able to add a depth + stencil surface at a later stage when you need it.
900 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
901 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
902 * context, need torecreate shaders, textures and other resources.
904 * The context manager already takes care of the state problem and for the other tasks code from Reset
905 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
906 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
907 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
908 * issue needs to be fixed. */
909 if (ds_format_desc
->format
!= WINED3DFMT_D24S8
)
911 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
912 ds_format_desc
= getFormatDescEntry(WINED3DFMT_D24S8
, &This
->adapter
->gl_info
);
915 getDepthStencilBits(ds_format_desc
, &depthBits
, &stencilBits
);
917 for(matchtry
= 0; matchtry
< (sizeof(matches
) / sizeof(matches
[0])) && !iPixelFormat
; matchtry
++) {
918 for(i
=0; i
<nCfgs
; i
++) {
919 BOOL exactDepthMatch
= TRUE
;
920 WineD3D_PixelFormat
*cfg
= &This
->adapter
->cfgs
[i
];
922 /* For now only accept RGBA formats. Perhaps some day we will
923 * allow floating point formats for pbuffers. */
924 if(cfg
->iPixelType
!= WGL_TYPE_RGBA_ARB
)
927 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
928 if(!pbuffer
&& !(cfg
->windowDrawable
&& cfg
->doubleBuffer
))
931 /* We like to have aux buffers in backbuffer mode */
932 if(auxBuffers
&& !cfg
->auxBuffers
&& matches
[matchtry
].require_aux
)
935 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
936 if(pbuffer
&& (!cfg
->pbufferDrawable
|| cfg
->doubleBuffer
))
939 if(matches
[matchtry
].exact_color
) {
940 if(cfg
->redSize
!= redBits
)
942 if(cfg
->greenSize
!= greenBits
)
944 if(cfg
->blueSize
!= blueBits
)
947 if(cfg
->redSize
< redBits
)
949 if(cfg
->greenSize
< greenBits
)
951 if(cfg
->blueSize
< blueBits
)
954 if(matches
[matchtry
].exact_alpha
) {
955 if(cfg
->alphaSize
!= alphaBits
)
958 if(cfg
->alphaSize
< alphaBits
)
962 /* We try to locate a format which matches our requirements exactly. In case of
963 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
964 if(cfg
->depthSize
< depthBits
)
966 else if(cfg
->depthSize
> depthBits
)
967 exactDepthMatch
= FALSE
;
969 /* In all cases make sure the number of stencil bits matches our requirements
970 * even when we don't need stencil because it could affect performance EXCEPT
971 * on cards which don't offer depth formats without stencil like the i915 drivers
973 if(stencilBits
!= cfg
->stencilSize
&& !(This
->adapter
->brokenStencil
&& stencilBits
<= cfg
->stencilSize
))
976 /* Check multisampling support */
977 if(cfg
->numSamples
!= numSamples
)
980 /* When we have passed all the checks then we have found a format which matches our
981 * requirements. Note that we only check for a limit number of capabilities right now,
982 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
983 * can still differ in things like multisampling, stereo, SRGB and other flags.
986 /* Exit the loop as we have found a format :) */
987 if(exactDepthMatch
) {
988 iPixelFormat
= cfg
->iPixelFormat
;
990 } else if(!iPixelFormat
) {
991 /* In the end we might end up with a format which doesn't exactly match our depth
992 * requirements. Accept the first format we found because formats with higher iPixelFormat
993 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
994 iPixelFormat
= cfg
->iPixelFormat
;
999 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1000 if(!iPixelFormat
&& !findCompatible
) {
1001 ERR("Can't find a suitable iPixelFormat\n");
1003 } else if(!iPixelFormat
) {
1004 PIXELFORMATDESCRIPTOR pfd
;
1006 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1007 /* PixelFormat selection */
1008 ZeroMemory(&pfd
, sizeof(pfd
));
1009 pfd
.nSize
= sizeof(pfd
);
1011 pfd
.dwFlags
= PFD_SUPPORT_OPENGL
| PFD_DOUBLEBUFFER
| PFD_DRAW_TO_WINDOW
;/*PFD_GENERIC_ACCELERATED*/
1012 pfd
.iPixelType
= PFD_TYPE_RGBA
;
1013 pfd
.cAlphaBits
= alphaBits
;
1014 pfd
.cColorBits
= colorBits
;
1015 pfd
.cDepthBits
= depthBits
;
1016 pfd
.cStencilBits
= stencilBits
;
1017 pfd
.iLayerType
= PFD_MAIN_PLANE
;
1019 iPixelFormat
= ChoosePixelFormat(hdc
, &pfd
);
1021 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1022 ERR("Can't find a suitable iPixelFormat\n");
1027 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1028 iPixelFormat
, debug_d3dformat(color_format_desc
->format
), debug_d3dformat(ds_format_desc
->format
));
1029 return iPixelFormat
;
1032 /*****************************************************************************
1035 * Creates a new context for a window, or a pbuffer context.
1038 * This: Device to activate the context for
1039 * target: Surface this context will render to
1040 * win_handle: handle to the window which we are drawing to
1041 * create_pbuffer: tells whether to create a pbuffer or not
1042 * pPresentParameters: contains the pixelformats to use for onscreen rendering
1044 *****************************************************************************/
1045 WineD3DContext
*CreateContext(IWineD3DDeviceImpl
*This
, IWineD3DSurfaceImpl
*target
, HWND win_handle
, BOOL create_pbuffer
, const WINED3DPRESENT_PARAMETERS
*pPresentParms
) {
1046 const struct wined3d_gl_info
*gl_info
= &This
->adapter
->gl_info
;
1047 HPBUFFERARB pbuffer
= NULL
;
1048 WineD3DContext
*ret
= NULL
;
1053 TRACE("(%p): Creating a %s context for render target %p\n", This
, create_pbuffer
? "offscreen" : "onscreen", target
);
1055 if(create_pbuffer
) {
1056 HDC hdc_parent
= GetDC(win_handle
);
1057 int iPixelFormat
= 0;
1059 IWineD3DSurface
*StencilSurface
= This
->stencilBufferTarget
;
1060 const struct GlPixelFormatDesc
*ds_format_desc
= StencilSurface
1061 ? ((IWineD3DSurfaceImpl
*)StencilSurface
)->resource
.format_desc
1062 : getFormatDescEntry(WINED3DFMT_UNKNOWN
, &This
->adapter
->gl_info
);
1064 /* Try to find a pixel format with pbuffer support. */
1065 iPixelFormat
= WineD3D_ChoosePixelFormat(This
, hdc_parent
, target
->resource
.format_desc
,
1066 ds_format_desc
, FALSE
/* auxBuffers */, 0 /* numSamples */, TRUE
/* PBUFFER */,
1067 FALSE
/* findCompatible */);
1069 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1071 /* For some reason we weren't able to find a format, try to find something instead of crashing.
1072 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
1073 iPixelFormat
= WineD3D_ChoosePixelFormat(This
, hdc_parent
, target
->resource
.format_desc
,
1074 ds_format_desc
, FALSE
/* auxBuffer */, 0 /* numSamples */, TRUE
/* PBUFFER */,
1075 TRUE
/* findCompatible */);
1078 /* This shouldn't happen as ChoosePixelFormat always returns something */
1080 ERR("Unable to locate a pixel format for a pbuffer\n");
1081 ReleaseDC(win_handle
, hdc_parent
);
1085 TRACE("Creating a pBuffer drawable for the new context\n");
1086 pbuffer
= GL_EXTCALL(wglCreatePbufferARB(hdc_parent
, iPixelFormat
, target
->currentDesc
.Width
, target
->currentDesc
.Height
, 0));
1088 ERR("Cannot create a pbuffer\n");
1089 ReleaseDC(win_handle
, hdc_parent
);
1093 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
1094 hdc
= GL_EXTCALL(wglGetPbufferDCARB(pbuffer
));
1096 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer
);
1097 GL_EXTCALL(wglDestroyPbufferARB(pbuffer
));
1098 ReleaseDC(win_handle
, hdc_parent
);
1101 ReleaseDC(win_handle
, hdc_parent
);
1103 PIXELFORMATDESCRIPTOR pfd
;
1106 const struct GlPixelFormatDesc
*color_format_desc
= target
->resource
.format_desc
;
1107 const struct GlPixelFormatDesc
*ds_format_desc
= getFormatDescEntry(WINED3DFMT_UNKNOWN
,
1108 &This
->adapter
->gl_info
);
1109 BOOL auxBuffers
= FALSE
;
1112 hdc
= GetDC(win_handle
);
1114 ERR("Cannot retrieve a device context!\n");
1118 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1119 if(wined3d_settings
.offscreen_rendering_mode
== ORM_BACKBUFFER
) {
1122 if (color_format_desc
->format
== WINED3DFMT_X4R4G4B4
)
1123 color_format_desc
= getFormatDescEntry(WINED3DFMT_A4R4G4B4
, &This
->adapter
->gl_info
);
1124 else if (color_format_desc
->format
== WINED3DFMT_X8R8G8B8
)
1125 color_format_desc
= getFormatDescEntry(WINED3DFMT_A8R8G8B8
, &This
->adapter
->gl_info
);
1128 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
1129 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
1130 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
1131 * a format with 8bit alpha, so request A8R8G8B8. */
1132 if (color_format_desc
->format
== WINED3DFMT_P8
)
1133 color_format_desc
= getFormatDescEntry(WINED3DFMT_A8R8G8B8
, &This
->adapter
->gl_info
);
1135 /* Retrieve the depth stencil format from the present parameters.
1136 * The choice of the proper format can give a nice performance boost
1137 * in case of GPU limited programs. */
1138 if(pPresentParms
->EnableAutoDepthStencil
) {
1139 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms
->AutoDepthStencilFormat
));
1140 ds_format_desc
= getFormatDescEntry(pPresentParms
->AutoDepthStencilFormat
, &This
->adapter
->gl_info
);
1143 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
1144 if(pPresentParms
->MultiSampleType
&& (pPresentParms
->SwapEffect
== WINED3DSWAPEFFECT_DISCARD
)) {
1145 if(!GL_SUPPORT(ARB_MULTISAMPLE
))
1146 ERR("The program is requesting multisampling without support!\n");
1148 ERR("Requesting MultiSampleType=%d\n", pPresentParms
->MultiSampleType
);
1149 numSamples
= pPresentParms
->MultiSampleType
;
1153 /* Try to find a pixel format which matches our requirements */
1154 iPixelFormat
= WineD3D_ChoosePixelFormat(This
, hdc
, color_format_desc
, ds_format_desc
,
1155 auxBuffers
, numSamples
, FALSE
/* PBUFFER */, FALSE
/* findCompatible */);
1157 /* Try to locate a compatible format if we weren't able to find anything */
1159 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1160 iPixelFormat
= WineD3D_ChoosePixelFormat(This
, hdc
, color_format_desc
, ds_format_desc
,
1161 auxBuffers
, 0 /* numSamples */, FALSE
/* PBUFFER */, TRUE
/* findCompatible */ );
1164 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1166 ERR("Can't find a suitable iPixelFormat\n");
1170 DescribePixelFormat(hdc
, iPixelFormat
, sizeof(pfd
), &pfd
);
1171 res
= SetPixelFormat(hdc
, iPixelFormat
, NULL
);
1173 int oldPixelFormat
= GetPixelFormat(hdc
);
1175 /* By default WGL doesn't allow pixel format adjustments but we need it here.
1176 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
1177 * set the pixel format multiple times. Only use it when it is really needed. */
1179 if(oldPixelFormat
== iPixelFormat
) {
1180 /* We don't have to do anything as the formats are the same :) */
1181 } else if(oldPixelFormat
&& GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH
)) {
1182 res
= GL_EXTCALL(wglSetPixelFormatWINE(hdc
, iPixelFormat
, NULL
));
1185 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc
, iPixelFormat
);
1188 } else if(oldPixelFormat
) {
1189 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
1190 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
1191 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc
, oldPixelFormat
);
1193 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc
, iPixelFormat
);
1199 ctx
= pwglCreateContext(hdc
);
1200 if (This
->numContexts
)
1202 if (!pwglShareLists(This
->contexts
[0]->glCtx
, ctx
))
1204 DWORD err
= GetLastError();
1205 ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1206 This
->contexts
[0]->glCtx
, ctx
, err
);
1211 ERR("Failed to create a WGL context\n");
1212 if(create_pbuffer
) {
1213 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer
, hdc
));
1214 GL_EXTCALL(wglDestroyPbufferARB(pbuffer
));
1218 ret
= AddContextToArray(This
, win_handle
, hdc
, ctx
, pbuffer
);
1220 ERR("Failed to add the newly created context to the context list\n");
1221 if (!pwglDeleteContext(ctx
))
1223 DWORD err
= GetLastError();
1224 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx
, err
);
1226 if(create_pbuffer
) {
1227 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer
, hdc
));
1228 GL_EXTCALL(wglDestroyPbufferARB(pbuffer
));
1232 ret
->gl_info
= &This
->adapter
->gl_info
;
1233 ret
->surface
= (IWineD3DSurface
*) target
;
1234 ret
->current_rt
= (IWineD3DSurface
*)target
;
1235 ret
->isPBuffer
= create_pbuffer
;
1236 ret
->tid
= GetCurrentThreadId();
1237 if(This
->shader_backend
->shader_dirtifyable_constants((IWineD3DDevice
*) This
)) {
1238 /* Create the dirty constants array and initialize them to dirty */
1239 ret
->vshader_const_dirty
= HeapAlloc(GetProcessHeap(), 0,
1240 sizeof(*ret
->vshader_const_dirty
) * GL_LIMITS(vshader_constantsF
));
1241 ret
->pshader_const_dirty
= HeapAlloc(GetProcessHeap(), 0,
1242 sizeof(*ret
->pshader_const_dirty
) * GL_LIMITS(pshader_constantsF
));
1243 memset(ret
->vshader_const_dirty
, 1,
1244 sizeof(*ret
->vshader_const_dirty
) * GL_LIMITS(vshader_constantsF
));
1245 memset(ret
->pshader_const_dirty
, 1,
1246 sizeof(*ret
->pshader_const_dirty
) * GL_LIMITS(pshader_constantsF
));
1249 ret
->free_occlusion_query_size
= 4;
1250 ret
->free_occlusion_queries
= HeapAlloc(GetProcessHeap(), 0,
1251 ret
->free_occlusion_query_size
* sizeof(*ret
->free_occlusion_queries
));
1252 if (!ret
->free_occlusion_queries
) goto out
;
1254 list_init(&ret
->occlusion_queries
);
1256 ret
->free_event_query_size
= 4;
1257 ret
->free_event_queries
= HeapAlloc(GetProcessHeap(), 0,
1258 ret
->free_event_query_size
* sizeof(*ret
->free_event_queries
));
1259 if (!ret
->free_event_queries
) goto out
;
1261 list_init(&ret
->event_queries
);
1263 TRACE("Successfully created new context %p\n", ret
);
1265 list_init(&ret
->fbo_list
);
1267 /* Set up the context defaults */
1268 if (!context_set_current(ret
))
1270 ERR("Cannot activate context to set up defaults\n");
1276 glGetIntegerv(GL_AUX_BUFFERS
, &ret
->aux_buffers
);
1278 TRACE("Setting up the screen\n");
1279 /* Clear the screen */
1280 glClearColor(1.0f
, 0.0f
, 0.0f
, 0.0f
);
1281 checkGLcall("glClearColor");
1284 glClearStencil(0xffff);
1286 checkGLcall("glClear");
1288 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER
, GL_TRUE
);
1289 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1291 glTexEnvf(GL_TEXTURE_ENV
, GL_TEXTURE_ENV_MODE
, GL_COMBINE_EXT
);
1292 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1294 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL
, GL_SEPARATE_SPECULAR_COLOR
);
1295 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1297 glPixelStorei(GL_PACK_ALIGNMENT
, This
->surface_alignment
);
1298 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
1299 glPixelStorei(GL_UNPACK_ALIGNMENT
, This
->surface_alignment
);
1300 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
1302 if(GL_SUPPORT(APPLE_CLIENT_STORAGE
)) {
1303 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
1304 * and textures in DIB sections(due to the memory protection).
1306 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE
, GL_TRUE
);
1307 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1309 if(GL_SUPPORT(ARB_VERTEX_BLEND
)) {
1310 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
1311 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
1312 * GL_VERTEX_BLEND_ARB isn't enabled too
1314 glEnable(GL_WEIGHT_SUM_UNITY_ARB
);
1315 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1317 if(GL_SUPPORT(NV_TEXTURE_SHADER2
)) {
1318 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1319 * the previous texture where to source the offset from is always unit - 1.
1321 for(s
= 1; s
< GL_LIMITS(textures
); s
++) {
1322 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB
+ s
));
1323 glTexEnvi(GL_TEXTURE_SHADER_NV
, GL_PREVIOUS_TEXTURE_INPUT_NV
, GL_TEXTURE0_ARB
+ s
- 1);
1324 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1327 if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM
)) {
1328 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1329 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1330 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1331 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1334 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1335 * program and the dummy program is destroyed when the context is destroyed.
1337 const char *dummy_program
=
1339 "MOV result.color, fragment.color.primary;\n"
1341 GL_EXTCALL(glGenProgramsARB(1, &ret
->dummy_arbfp_prog
));
1342 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB
, ret
->dummy_arbfp_prog
));
1343 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB
, GL_PROGRAM_FORMAT_ASCII_ARB
, strlen(dummy_program
), dummy_program
));
1346 for(s
= 0; s
< GL_LIMITS(point_sprite_units
); s
++) {
1347 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB
+ s
));
1348 glTexEnvi(GL_POINT_SPRITE_ARB
, GL_COORD_REPLACE_ARB
, GL_TRUE
);
1349 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1353 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, TRUE
);
1360 HeapFree(GetProcessHeap(), 0, ret
->free_event_queries
);
1361 HeapFree(GetProcessHeap(), 0, ret
->free_occlusion_queries
);
1362 HeapFree(GetProcessHeap(), 0, ret
->pshader_const_dirty
);
1363 HeapFree(GetProcessHeap(), 0, ret
->vshader_const_dirty
);
1364 HeapFree(GetProcessHeap(), 0, ret
);
1369 /*****************************************************************************
1370 * RemoveContextFromArray
1372 * Removes a context from the context manager. The opengl context is not
1373 * destroyed or unset. context is not a valid pointer after that call.
1375 * Similar to the former call this isn't a performance critical function. A
1376 * helper function for DestroyContext.
1379 * This: Device to activate the context for
1380 * context: Context to remove
1382 *****************************************************************************/
1383 static void RemoveContextFromArray(IWineD3DDeviceImpl
*This
, WineD3DContext
*context
) {
1384 WineD3DContext
**new_array
;
1388 TRACE("Removing ctx %p\n", context
);
1390 for (i
= 0; i
< This
->numContexts
; ++i
)
1392 if (This
->contexts
[i
] == context
)
1401 ERR("Context %p doesn't exist in context array\n", context
);
1405 while (i
< This
->numContexts
- 1)
1407 This
->contexts
[i
] = This
->contexts
[i
+ 1];
1411 --This
->numContexts
;
1412 if (!This
->numContexts
)
1414 HeapFree(GetProcessHeap(), 0, This
->contexts
);
1415 This
->contexts
= NULL
;
1419 new_array
= HeapReAlloc(GetProcessHeap(), 0, This
->contexts
, This
->numContexts
* sizeof(*This
->contexts
));
1422 ERR("Failed to shrink context array. Oh well.\n");
1426 This
->contexts
= new_array
;
1429 /*****************************************************************************
1432 * Destroys a wineD3DContext
1435 * This: Device to activate the context for
1436 * context: Context to destroy
1438 *****************************************************************************/
1439 void DestroyContext(IWineD3DDeviceImpl
*This
, WineD3DContext
*context
)
1443 TRACE("Destroying ctx %p\n", context
);
1445 if (context
->tid
== GetCurrentThreadId() || !context
->current
)
1447 context_destroy_gl_resources(context
);
1450 if (!context_set_current(NULL
))
1452 ERR("Failed to clear current D3D context.\n");
1457 context
->destroyed
= 1;
1461 HeapFree(GetProcessHeap(), 0, context
->vshader_const_dirty
);
1462 HeapFree(GetProcessHeap(), 0, context
->pshader_const_dirty
);
1463 RemoveContextFromArray(This
, context
);
1464 if (destroy
) HeapFree(GetProcessHeap(), 0, context
);
1467 /* GL locking is done by the caller */
1468 static inline void set_blit_dimension(UINT width
, UINT height
) {
1469 glMatrixMode(GL_PROJECTION
);
1470 checkGLcall("glMatrixMode(GL_PROJECTION)");
1472 checkGLcall("glLoadIdentity()");
1473 glOrtho(0, width
, height
, 0, 0.0, -1.0);
1474 checkGLcall("glOrtho");
1475 glViewport(0, 0, width
, height
);
1476 checkGLcall("glViewport");
1479 /*****************************************************************************
1482 * Sets up a context for DirectDraw blitting.
1483 * All texture units are disabled, texture unit 0 is set as current unit
1484 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1485 * color writing enabled for all channels
1486 * register combiners disabled, shaders disabled
1487 * world matrix is set to identity, texture matrix 0 too
1488 * projection matrix is setup for drawing screen coordinates
1491 * This: Device to activate the context for
1492 * context: Context to setup
1493 * width: render target width
1494 * height: render target height
1496 *****************************************************************************/
1497 /* Context activation is done by the caller. */
1498 static inline void SetupForBlit(IWineD3DDeviceImpl
*This
, WineD3DContext
*context
, UINT width
, UINT height
) {
1500 const struct StateEntry
*StateTable
= This
->StateTable
;
1501 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
1503 TRACE("Setting up context %p for blitting\n", context
);
1504 if(context
->last_was_blit
) {
1505 if(context
->blit_w
!= width
|| context
->blit_h
!= height
) {
1507 set_blit_dimension(width
, height
);
1509 context
->blit_w
= width
; context
->blit_h
= height
;
1510 /* No need to dirtify here, the states are still dirtified because they weren't
1511 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1515 TRACE("Context is already set up for blitting, nothing to do\n");
1518 context
->last_was_blit
= TRUE
;
1520 /* TODO: Use a display list */
1522 /* Disable shaders */
1524 This
->shader_backend
->shader_select((IWineD3DDevice
*)This
, FALSE
, FALSE
);
1527 Context_MarkStateDirty(context
, STATE_VSHADER
, StateTable
);
1528 Context_MarkStateDirty(context
, STATE_PIXELSHADER
, StateTable
);
1530 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1531 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1532 * which can safely be called from here, we only lock once instead locking/unlocking
1533 * after each GL call.
1537 /* Disable all textures. The caller can then bind a texture it wants to blit
1540 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1541 * function texture unit. No need to care for higher samplers
1543 for(i
= GL_LIMITS(textures
) - 1; i
> 0 ; i
--) {
1544 sampler
= This
->rev_tex_unit_map
[i
];
1545 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB
+ i
));
1546 checkGLcall("glActiveTextureARB");
1548 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP
)) {
1549 glDisable(GL_TEXTURE_CUBE_MAP_ARB
);
1550 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1552 glDisable(GL_TEXTURE_3D
);
1553 checkGLcall("glDisable GL_TEXTURE_3D");
1554 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE
)) {
1555 glDisable(GL_TEXTURE_RECTANGLE_ARB
);
1556 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1558 glDisable(GL_TEXTURE_2D
);
1559 checkGLcall("glDisable GL_TEXTURE_2D");
1561 glTexEnvi(GL_TEXTURE_ENV
, GL_TEXTURE_ENV_MODE
, GL_REPLACE
);
1562 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1564 if (sampler
!= -1) {
1565 if (sampler
< MAX_TEXTURES
) {
1566 Context_MarkStateDirty(context
, STATE_TEXTURESTAGE(sampler
, WINED3DTSS_COLOROP
), StateTable
);
1568 Context_MarkStateDirty(context
, STATE_SAMPLER(sampler
), StateTable
);
1571 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB
));
1572 checkGLcall("glActiveTextureARB");
1574 sampler
= This
->rev_tex_unit_map
[0];
1576 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP
)) {
1577 glDisable(GL_TEXTURE_CUBE_MAP_ARB
);
1578 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1580 glDisable(GL_TEXTURE_3D
);
1581 checkGLcall("glDisable GL_TEXTURE_3D");
1582 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE
)) {
1583 glDisable(GL_TEXTURE_RECTANGLE_ARB
);
1584 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1586 glDisable(GL_TEXTURE_2D
);
1587 checkGLcall("glDisable GL_TEXTURE_2D");
1589 glTexEnvi(GL_TEXTURE_ENV
, GL_TEXTURE_ENV_MODE
, GL_REPLACE
);
1591 glMatrixMode(GL_TEXTURE
);
1592 checkGLcall("glMatrixMode(GL_TEXTURE)");
1594 checkGLcall("glLoadIdentity()");
1596 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS
)) {
1597 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT
,
1598 GL_TEXTURE_LOD_BIAS_EXT
,
1600 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1603 if (sampler
!= -1) {
1604 if (sampler
< MAX_TEXTURES
) {
1605 Context_MarkStateDirty(context
, STATE_TRANSFORM(WINED3DTS_TEXTURE0
+ sampler
), StateTable
);
1606 Context_MarkStateDirty(context
, STATE_TEXTURESTAGE(sampler
, WINED3DTSS_COLOROP
), StateTable
);
1608 Context_MarkStateDirty(context
, STATE_SAMPLER(sampler
), StateTable
);
1611 /* Other misc states */
1612 glDisable(GL_ALPHA_TEST
);
1613 checkGLcall("glDisable(GL_ALPHA_TEST)");
1614 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ALPHATESTENABLE
), StateTable
);
1615 glDisable(GL_LIGHTING
);
1616 checkGLcall("glDisable GL_LIGHTING");
1617 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_LIGHTING
), StateTable
);
1618 glDisable(GL_DEPTH_TEST
);
1619 checkGLcall("glDisable GL_DEPTH_TEST");
1620 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ZENABLE
), StateTable
);
1621 glDisableWINE(GL_FOG
);
1622 checkGLcall("glDisable GL_FOG");
1623 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_FOGENABLE
), StateTable
);
1624 glDisable(GL_BLEND
);
1625 checkGLcall("glDisable GL_BLEND");
1626 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE
), StateTable
);
1627 glDisable(GL_CULL_FACE
);
1628 checkGLcall("glDisable GL_CULL_FACE");
1629 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_CULLMODE
), StateTable
);
1630 glDisable(GL_STENCIL_TEST
);
1631 checkGLcall("glDisable GL_STENCIL_TEST");
1632 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_STENCILENABLE
), StateTable
);
1633 glDisable(GL_SCISSOR_TEST
);
1634 checkGLcall("glDisable GL_SCISSOR_TEST");
1635 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE
), StateTable
);
1636 if(GL_SUPPORT(ARB_POINT_SPRITE
)) {
1637 glDisable(GL_POINT_SPRITE_ARB
);
1638 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1639 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE
), StateTable
);
1641 glColorMask(GL_TRUE
, GL_TRUE
,GL_TRUE
,GL_TRUE
);
1642 checkGLcall("glColorMask");
1643 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_CLIPPING
), StateTable
);
1644 if (GL_SUPPORT(EXT_SECONDARY_COLOR
)) {
1645 glDisable(GL_COLOR_SUM_EXT
);
1646 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_SPECULARENABLE
), StateTable
);
1647 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1650 /* Setup transforms */
1651 glMatrixMode(GL_MODELVIEW
);
1652 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1654 checkGLcall("glLoadIdentity()");
1655 Context_MarkStateDirty(context
, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable
);
1657 context
->last_was_rhw
= TRUE
;
1658 Context_MarkStateDirty(context
, STATE_VDECL
, StateTable
); /* because of last_was_rhw = TRUE */
1660 glDisable(GL_CLIP_PLANE0
); checkGLcall("glDisable(clip plane 0)");
1661 glDisable(GL_CLIP_PLANE1
); checkGLcall("glDisable(clip plane 1)");
1662 glDisable(GL_CLIP_PLANE2
); checkGLcall("glDisable(clip plane 2)");
1663 glDisable(GL_CLIP_PLANE3
); checkGLcall("glDisable(clip plane 3)");
1664 glDisable(GL_CLIP_PLANE4
); checkGLcall("glDisable(clip plane 4)");
1665 glDisable(GL_CLIP_PLANE5
); checkGLcall("glDisable(clip plane 5)");
1666 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_CLIPPING
), StateTable
);
1668 set_blit_dimension(width
, height
);
1672 context
->blit_w
= width
; context
->blit_h
= height
;
1673 Context_MarkStateDirty(context
, STATE_VIEWPORT
, StateTable
);
1674 Context_MarkStateDirty(context
, STATE_TRANSFORM(WINED3DTS_PROJECTION
), StateTable
);
1677 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, FALSE
);
1680 /*****************************************************************************
1681 * findThreadContextForSwapChain
1683 * Searches a swapchain for all contexts and picks one for the thread tid.
1684 * If none can be found the swapchain is requested to create a new context
1686 *****************************************************************************/
1687 static WineD3DContext
*findThreadContextForSwapChain(IWineD3DSwapChain
*swapchain
, DWORD tid
) {
1690 for(i
= 0; i
< ((IWineD3DSwapChainImpl
*) swapchain
)->num_contexts
; i
++) {
1691 if(((IWineD3DSwapChainImpl
*) swapchain
)->context
[i
]->tid
== tid
) {
1692 return ((IWineD3DSwapChainImpl
*) swapchain
)->context
[i
];
1697 /* Create a new context for the thread */
1698 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain
);
1701 /*****************************************************************************
1704 * Finds a context for the current render target and thread
1707 * target: Render target to find the context for
1708 * tid: Thread to activate the context for
1710 * Returns: The needed context
1712 *****************************************************************************/
1713 static inline WineD3DContext
*FindContext(IWineD3DDeviceImpl
*This
, IWineD3DSurface
*target
, DWORD tid
) {
1714 IWineD3DSwapChain
*swapchain
= NULL
;
1715 BOOL readTexture
= wined3d_settings
.offscreen_rendering_mode
!= ORM_FBO
&& This
->render_offscreen
;
1716 struct WineD3DContext
*current_context
= context_get_current();
1717 BOOL oldRenderOffscreen
= This
->render_offscreen
;
1718 const struct StateEntry
*StateTable
= This
->StateTable
;
1719 const struct GlPixelFormatDesc
*old
, *new;
1720 struct WineD3DContext
*context
;
1722 if (current_context
&& current_context
->destroyed
) current_context
= NULL
;
1727 && ((IWineD3DSurfaceImpl
*)current_context
->surface
)->resource
.wineD3DDevice
== This
)
1729 target
= current_context
->current_rt
;
1733 IWineD3DSwapChainImpl
*swapchain
= (IWineD3DSwapChainImpl
*)This
->swapchains
[0];
1734 if (swapchain
->backBuffer
) target
= swapchain
->backBuffer
[0];
1735 else target
= swapchain
->frontBuffer
;
1739 if (current_context
&& current_context
->current_rt
== target
)
1741 return current_context
;
1744 if (SUCCEEDED(IWineD3DSurface_GetContainer(target
, &IID_IWineD3DSwapChain
, (void **)&swapchain
))) {
1745 TRACE("Rendering onscreen\n");
1747 context
= findThreadContextForSwapChain(swapchain
, tid
);
1749 This
->render_offscreen
= FALSE
;
1750 /* The context != This->activeContext will catch a NOP context change. This can occur
1751 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1752 * rendering. No context change is needed in that case
1755 if(wined3d_settings
.offscreen_rendering_mode
== ORM_PBUFFER
) {
1756 if(This
->pbufferContext
&& tid
== This
->pbufferContext
->tid
) {
1757 This
->pbufferContext
->tid
= 0;
1760 IWineD3DSwapChain_Release(swapchain
);
1764 TRACE("Rendering offscreen\n");
1765 This
->render_offscreen
= TRUE
;
1768 if (wined3d_settings
.offscreen_rendering_mode
== ORM_PBUFFER
)
1770 IWineD3DSurfaceImpl
*targetimpl
= (IWineD3DSurfaceImpl
*)target
;
1771 if (!This
->pbufferContext
1772 || This
->pbufferWidth
< targetimpl
->currentDesc
.Width
1773 || This
->pbufferHeight
< targetimpl
->currentDesc
.Height
)
1775 if (This
->pbufferContext
) DestroyContext(This
, This
->pbufferContext
);
1777 /* The display is irrelevant here, the window is 0. But
1778 * CreateContext needs a valid X connection. Create the context
1779 * on the same server as the primary swapchain. The primary
1780 * swapchain is exists at this point. */
1781 This
->pbufferContext
= CreateContext(This
, targetimpl
,
1782 ((IWineD3DSwapChainImpl
*)This
->swapchains
[0])->context
[0]->win_handle
,
1783 TRUE
/* pbuffer */, &((IWineD3DSwapChainImpl
*)This
->swapchains
[0])->presentParms
);
1784 This
->pbufferWidth
= targetimpl
->currentDesc
.Width
;
1785 This
->pbufferHeight
= targetimpl
->currentDesc
.Height
;
1788 if (This
->pbufferContext
)
1790 if (This
->pbufferContext
->tid
&& This
->pbufferContext
->tid
!= tid
)
1792 FIXME("The PBuffer context is only supported for one thread for now!\n");
1794 This
->pbufferContext
->tid
= tid
;
1795 context
= This
->pbufferContext
;
1799 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering.\n");
1800 wined3d_settings
.offscreen_rendering_mode
= ORM_BACKBUFFER
;
1806 /* Stay with the currently active context. */
1808 && ((IWineD3DSurfaceImpl
*)current_context
->surface
)->resource
.wineD3DDevice
== This
)
1810 context
= current_context
;
1814 /* This may happen if the app jumps straight into offscreen rendering
1815 * Start using the context of the primary swapchain. tid == 0 is no problem
1816 * for findThreadContextForSwapChain.
1818 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1819 * is perfect to call. */
1820 context
= findThreadContextForSwapChain(This
->swapchains
[0], tid
);
1825 if (This
->render_offscreen
!= oldRenderOffscreen
)
1827 Context_MarkStateDirty(context
, WINED3DTS_PROJECTION
, StateTable
);
1828 Context_MarkStateDirty(context
, STATE_VDECL
, StateTable
);
1829 Context_MarkStateDirty(context
, STATE_VIEWPORT
, StateTable
);
1830 Context_MarkStateDirty(context
, STATE_SCISSORRECT
, StateTable
);
1831 Context_MarkStateDirty(context
, STATE_FRONTFACE
, StateTable
);
1834 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1835 * the alpha blend state changes with different render target formats. */
1836 old
= ((IWineD3DSurfaceImpl
*)context
->current_rt
)->resource
.format_desc
;
1837 new = ((IWineD3DSurfaceImpl
*)target
)->resource
.format_desc
;
1838 if (old
->format
!= new->format
)
1840 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
1841 if ((old
->alpha_mask
&& !new->alpha_mask
) || (!old
->alpha_mask
&& new->alpha_mask
)
1842 || !(new->Flags
& WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING
))
1844 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE
), StateTable
);
1848 /* When switching away from an offscreen render target, and we're not using FBOs,
1849 * we have to read the drawable into the texture. This is done via PreLoad(and
1850 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1851 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1852 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1853 * is read. This leads to these possible situations:
1855 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1856 * Nothing to do, we don't even reach this code in this case...
1858 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1859 * The currently active context is OK for readback. Call PreLoad, and it
1862 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1863 * Nothing to do - the drawable is unchanged
1865 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1866 * This is tricky. We have to get a context with the old drawable from somewhere
1867 * before we can switch to the new context. In this case, PreLoad calls
1868 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1869 * is case (2) then. The old drawable is activated for the new thread, and the
1870 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1871 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1872 * target for the new thread
1874 if (readTexture
&& context
->current_rt
!= target
)
1876 BOOL oldInDraw
= This
->isInDraw
;
1878 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1879 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1880 * when using offscreen rendering with multithreading
1882 This
->isInDraw
= TRUE
;
1884 /* Do that before switching the context:
1885 * Read the back buffer of the old drawable into the destination texture
1887 if (((IWineD3DSurfaceImpl
*)context
->current_rt
)->texture_name_srgb
)
1889 surface_internal_preload(context
->current_rt
, SRGB_BOTH
);
1891 surface_internal_preload(context
->current_rt
, SRGB_RGB
);
1894 /* Assume that the drawable will be modified by some other things now */
1895 IWineD3DSurface_ModifyLocation(context
->current_rt
, SFLAG_INDRAWABLE
, FALSE
);
1897 This
->isInDraw
= oldInDraw
;
1900 context
->draw_buffer_dirty
= TRUE
;
1901 context
->current_rt
= target
;
1906 /* Context activation is done by the caller. */
1907 static void context_apply_draw_buffer(struct WineD3DContext
*context
, BOOL blit
)
1909 const struct wined3d_gl_info
*gl_info
= context
->gl_info
;
1910 IWineD3DSurface
*rt
= context
->current_rt
;
1911 IWineD3DSwapChain
*swapchain
;
1912 IWineD3DDeviceImpl
*device
;
1914 device
= ((IWineD3DSurfaceImpl
*)rt
)->resource
.wineD3DDevice
;
1915 if (SUCCEEDED(IWineD3DSurface_GetContainer(rt
, &IID_IWineD3DSwapChain
, (void **)&swapchain
)))
1917 IWineD3DSwapChain_Release((IUnknown
*)swapchain
);
1919 glDrawBuffer(surface_get_gl_buffer(rt
, swapchain
));
1920 checkGLcall("glDrawBuffers()");
1926 if (wined3d_settings
.offscreen_rendering_mode
== ORM_FBO
)
1930 if (GL_SUPPORT(ARB_DRAW_BUFFERS
))
1932 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers
), device
->draw_buffers
));
1933 checkGLcall("glDrawBuffers()");
1937 glDrawBuffer(device
->draw_buffers
[0]);
1938 checkGLcall("glDrawBuffer()");
1941 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT
);
1942 checkGLcall("glDrawBuffer()");
1947 glDrawBuffer(device
->offscreenBuffer
);
1948 checkGLcall("glDrawBuffer()");
1954 /*****************************************************************************
1957 * Finds a rendering context and drawable matching the device and render
1958 * target for the current thread, activates them and puts them into the
1962 * This: Device to activate the context for
1963 * target: Requested render target
1964 * usage: Prepares the context for blitting, drawing or other actions
1966 *****************************************************************************/
1967 struct WineD3DContext
*ActivateContext(IWineD3DDeviceImpl
*This
, IWineD3DSurface
*target
, enum ContextUsage usage
)
1969 struct WineD3DContext
*current_context
= context_get_current();
1970 DWORD tid
= GetCurrentThreadId();
1971 DWORD i
, dirtyState
, idx
;
1973 WineD3DContext
*context
;
1974 const struct StateEntry
*StateTable
= This
->StateTable
;
1975 const struct wined3d_gl_info
*gl_info
;
1977 TRACE("(%p): Selecting context for render target %p, thread %d\n", This
, target
, tid
);
1979 context
= FindContext(This
, target
, tid
);
1981 gl_info
= context
->gl_info
;
1983 /* Activate the opengl context */
1984 if (context
!= current_context
)
1986 if (!context_set_current(context
)) ERR("Failed to activate the new context.\n");
1987 else This
->frag_pipe
->enable_extension((IWineD3DDevice
*)This
, !context
->last_was_blit
);
1989 if (context
->vshader_const_dirty
)
1991 memset(context
->vshader_const_dirty
, 1,
1992 sizeof(*context
->vshader_const_dirty
) * GL_LIMITS(vshader_constantsF
));
1993 This
->highest_dirty_vs_const
= GL_LIMITS(vshader_constantsF
);
1995 if (context
->pshader_const_dirty
)
1997 memset(context
->pshader_const_dirty
, 1,
1998 sizeof(*context
->pshader_const_dirty
) * GL_LIMITS(pshader_constantsF
));
1999 This
->highest_dirty_ps_const
= GL_LIMITS(pshader_constantsF
);
2004 case CTXUSAGE_CLEAR
:
2005 case CTXUSAGE_DRAWPRIM
:
2006 if (wined3d_settings
.offscreen_rendering_mode
== ORM_FBO
) {
2008 context_apply_fbo_state(context
);
2011 if (context
->draw_buffer_dirty
) {
2012 context_apply_draw_buffer(context
, FALSE
);
2013 context
->draw_buffer_dirty
= FALSE
;
2018 if (wined3d_settings
.offscreen_rendering_mode
== ORM_FBO
) {
2019 if (This
->render_offscreen
) {
2020 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
2022 context_bind_fbo(context
, GL_FRAMEBUFFER_EXT
, &context
->dst_fbo
);
2023 context_attach_surface_fbo(context
, GL_FRAMEBUFFER_EXT
, 0, target
);
2024 context_attach_depth_stencil_fbo(context
, GL_FRAMEBUFFER_EXT
, NULL
, FALSE
);
2028 context_bind_fbo(context
, GL_FRAMEBUFFER_EXT
, NULL
);
2031 context
->draw_buffer_dirty
= TRUE
;
2033 if (context
->draw_buffer_dirty
) {
2034 context_apply_draw_buffer(context
, TRUE
);
2035 if (wined3d_settings
.offscreen_rendering_mode
!= ORM_FBO
) {
2036 context
->draw_buffer_dirty
= FALSE
;
2046 case CTXUSAGE_RESOURCELOAD
:
2047 /* This does not require any special states to be set up */
2050 case CTXUSAGE_CLEAR
:
2051 if(context
->last_was_blit
) {
2052 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, TRUE
);
2055 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
2056 * blending when clearing improves the clearing performance incredibly.
2059 glDisable(GL_BLEND
);
2061 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE
), StateTable
);
2064 glEnable(GL_SCISSOR_TEST
);
2065 checkGLcall("glEnable GL_SCISSOR_TEST");
2067 context
->last_was_blit
= FALSE
;
2068 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE
), StateTable
);
2069 Context_MarkStateDirty(context
, STATE_SCISSORRECT
, StateTable
);
2072 case CTXUSAGE_DRAWPRIM
:
2073 /* This needs all dirty states applied */
2074 if(context
->last_was_blit
) {
2075 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, TRUE
);
2078 IWineD3DDeviceImpl_FindTexUnitMap(This
);
2081 for(i
=0; i
< context
->numDirtyEntries
; i
++) {
2082 dirtyState
= context
->dirtyArray
[i
];
2083 idx
= dirtyState
>> 5;
2084 shift
= dirtyState
& 0x1f;
2085 context
->isStateDirty
[idx
] &= ~(1 << shift
);
2086 StateTable
[dirtyState
].apply(dirtyState
, This
->stateBlock
, context
);
2089 context
->numDirtyEntries
= 0; /* This makes the whole list clean */
2090 context
->last_was_blit
= FALSE
;
2094 SetupForBlit(This
, context
,
2095 ((IWineD3DSurfaceImpl
*)target
)->currentDesc
.Width
,
2096 ((IWineD3DSurfaceImpl
*)target
)->currentDesc
.Height
);
2100 FIXME("Unexpected context usage requested\n");