push cc8bc80451cc24f4d7cf75168b569f0ebfe19547
[wine/hacks.git] / dlls / wined3d / context.c
blob81bddb18c22e8e638a02edf51247389073692905
1 /*
2 * Context and render target management in wined3d
4 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include <stdio.h>
23 #ifdef HAVE_FLOAT_H
24 # include <float.h>
25 #endif
26 #include "wined3d_private.h"
28 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
30 #define GLINFO_LOCATION This->adapter->gl_info
32 /* The last used device.
34 * If the application creates multiple devices and switches between them, ActivateContext has to
35 * change the opengl context. This flag allows to keep track which device is active
37 static IWineD3DDeviceImpl *last_device;
39 /* FBO helper functions */
41 /* GL locking is done by the caller */
42 void context_bind_fbo(IWineD3DDevice *iface, GLenum target, GLuint *fbo)
44 const IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
46 if (!*fbo)
48 GL_EXTCALL(glGenFramebuffersEXT(1, fbo));
49 checkGLcall("glGenFramebuffersEXT()");
50 TRACE("Created FBO %d\n", *fbo);
53 GL_EXTCALL(glBindFramebufferEXT(target, *fbo));
54 checkGLcall("glBindFramebuffer()");
57 /* GL locking is done by the caller */
58 static void context_clean_fbo_attachments(IWineD3DDeviceImpl *This)
60 unsigned int i;
62 for (i = 0; i < GL_LIMITS(buffers); ++i)
64 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, 0, 0));
65 checkGLcall("glFramebufferTexture2D()");
67 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
68 checkGLcall("glFramebufferTexture2D()");
70 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
71 checkGLcall("glFramebufferTexture2D()");
74 /* GL locking is done by the caller */
75 static void context_destroy_fbo(IWineD3DDeviceImpl *This, const GLuint *fbo)
77 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, *fbo));
78 checkGLcall("glBindFramebuffer()");
80 context_clean_fbo_attachments(This);
82 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
83 checkGLcall("glBindFramebuffer()");
84 GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo));
85 checkGLcall("glDeleteFramebuffers()");
88 /* GL locking is done by the caller */
89 static void context_apply_attachment_filter_states(IWineD3DDevice *iface, IWineD3DSurface *surface, BOOL force_preload)
91 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
92 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
93 IWineD3DBaseTextureImpl *texture_impl;
94 BOOL update_minfilter = FALSE;
95 BOOL update_magfilter = FALSE;
97 /* Update base texture states array */
98 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
100 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
101 || texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
103 texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
104 texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
105 update_minfilter = TRUE;
108 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
110 texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
111 update_magfilter = TRUE;
114 if (texture_impl->baseTexture.bindCount)
116 WARN("Render targets should not be bound to a sampler\n");
117 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(texture_impl->baseTexture.sampler));
120 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
123 if (update_minfilter || update_magfilter || force_preload)
125 GLenum target, bind_target;
126 GLint old_binding;
128 target = surface_impl->glDescription.target;
129 if (target == GL_TEXTURE_2D)
131 bind_target = GL_TEXTURE_2D;
132 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
133 } else if (target == GL_TEXTURE_RECTANGLE_ARB) {
134 bind_target = GL_TEXTURE_RECTANGLE_ARB;
135 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
136 } else {
137 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
138 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
141 surface_internal_preload(surface, SRGB_RGB);
143 glBindTexture(bind_target, surface_impl->glDescription.textureName);
144 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
145 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
146 glBindTexture(bind_target, old_binding);
149 checkGLcall("apply_attachment_filter_states()");
152 /* GL locking is done by the caller */
153 void context_attach_depth_stencil_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
155 IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
157 TRACE("Attach depth stencil %p\n", depth_stencil);
159 if (depth_stencil)
161 DWORD format_flags = depth_stencil_impl->resource.format_desc->Flags;
163 if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
165 if (format_flags & WINED3DFMT_FLAG_DEPTH)
167 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT,
168 GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
169 checkGLcall("glFramebufferRenderbufferEXT()");
172 if (format_flags & WINED3DFMT_FLAG_STENCIL)
174 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_STENCIL_ATTACHMENT_EXT,
175 GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
176 checkGLcall("glFramebufferRenderbufferEXT()");
179 else
181 context_apply_attachment_filter_states((IWineD3DDevice *)This, depth_stencil, TRUE);
183 if (format_flags & WINED3DFMT_FLAG_DEPTH)
185 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT,
186 depth_stencil_impl->glDescription.target, depth_stencil_impl->glDescription.textureName,
187 depth_stencil_impl->glDescription.level));
188 checkGLcall("glFramebufferTexture2DEXT()");
191 if (format_flags & WINED3DFMT_FLAG_STENCIL)
193 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_STENCIL_ATTACHMENT_EXT,
194 depth_stencil_impl->glDescription.target, depth_stencil_impl->glDescription.textureName,
195 depth_stencil_impl->glDescription.level));
196 checkGLcall("glFramebufferTexture2DEXT()");
200 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
202 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
203 checkGLcall("glFramebufferTexture2DEXT()");
206 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
208 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
209 checkGLcall("glFramebufferTexture2DEXT()");
212 else
214 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
215 checkGLcall("glFramebufferTexture2DEXT()");
217 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
218 checkGLcall("glFramebufferTexture2DEXT()");
222 /* GL locking is done by the caller */
223 void context_attach_surface_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
225 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
227 TRACE("Attach surface %p to %u\n", surface, idx);
229 if (surface)
231 context_apply_attachment_filter_states((IWineD3DDevice *)This, surface, TRUE);
233 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, surface_impl->glDescription.target,
234 surface_impl->glDescription.textureName, surface_impl->glDescription.level));
235 checkGLcall("glFramebufferTexture2DEXT()");
236 } else {
237 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, GL_TEXTURE_2D, 0, 0));
238 checkGLcall("glFramebufferTexture2DEXT()");
242 /* GL locking is done by the caller */
243 static void context_check_fbo_status(IWineD3DDevice *iface)
245 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
246 GLenum status;
248 status = GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
249 if (status == GL_FRAMEBUFFER_COMPLETE_EXT)
251 TRACE("FBO complete\n");
252 } else {
253 IWineD3DSurfaceImpl *attachment;
254 unsigned int i;
255 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
257 /* Dump the FBO attachments */
258 for (i = 0; i < GL_LIMITS(buffers); ++i)
260 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->render_targets[i];
261 if (attachment)
263 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
264 i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
265 attachment->pow2Width, attachment->pow2Height);
268 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->depth_stencil;
269 if (attachment)
271 FIXME("\tDepth attachment: (%p) %s %ux%u\n",
272 attachment, debug_d3dformat(attachment->resource.format_desc->format),
273 attachment->pow2Width, attachment->pow2Height);
278 static struct fbo_entry *context_create_fbo_entry(IWineD3DDevice *iface)
280 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
281 struct fbo_entry *entry;
283 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
284 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
285 memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
286 entry->depth_stencil = This->stencilBufferTarget;
287 entry->attached = FALSE;
288 entry->id = 0;
290 return entry;
293 /* GL locking is done by the caller */
294 static void context_reuse_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
296 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
298 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, entry->id));
299 checkGLcall("glBindFramebuffer()");
300 context_clean_fbo_attachments(This);
302 memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
303 entry->depth_stencil = This->stencilBufferTarget;
304 entry->attached = FALSE;
307 /* GL locking is done by the caller */
308 static void context_destroy_fbo_entry(IWineD3DDeviceImpl *This, WineD3DContext *context, struct fbo_entry *entry)
310 if (entry->id)
312 TRACE("Destroy FBO %d\n", entry->id);
313 context_destroy_fbo(This, &entry->id);
315 --context->fbo_entry_count;
316 list_remove(&entry->entry);
317 HeapFree(GetProcessHeap(), 0, entry->render_targets);
318 HeapFree(GetProcessHeap(), 0, entry);
322 /* GL locking is done by the caller */
323 static struct fbo_entry *context_find_fbo_entry(IWineD3DDevice *iface, WineD3DContext *context)
325 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
326 struct fbo_entry *entry;
328 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
330 if (!memcmp(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets))
331 && entry->depth_stencil == This->stencilBufferTarget)
333 list_remove(&entry->entry);
334 list_add_head(&context->fbo_list, &entry->entry);
335 return entry;
339 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
341 entry = context_create_fbo_entry(iface);
342 list_add_head(&context->fbo_list, &entry->entry);
343 ++context->fbo_entry_count;
345 else
347 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
348 context_reuse_fbo_entry(iface, entry);
349 list_remove(&entry->entry);
350 list_add_head(&context->fbo_list, &entry->entry);
353 return entry;
356 /* GL locking is done by the caller */
357 static void context_apply_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
359 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
360 unsigned int i;
362 context_bind_fbo(iface, GL_FRAMEBUFFER_EXT, &entry->id);
364 if (!entry->attached)
366 /* Apply render targets */
367 for (i = 0; i < GL_LIMITS(buffers); ++i)
369 IWineD3DSurface *render_target = This->render_targets[i];
370 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, i, render_target);
373 /* Apply depth targets */
374 if (This->stencilBufferTarget) {
375 unsigned int w = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Width;
376 unsigned int h = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Height;
378 surface_set_compatible_renderbuffer(This->stencilBufferTarget, w, h);
380 context_attach_depth_stencil_fbo(This, GL_FRAMEBUFFER_EXT, This->stencilBufferTarget, TRUE);
382 entry->attached = TRUE;
383 } else {
384 for (i = 0; i < GL_LIMITS(buffers); ++i)
386 if (This->render_targets[i])
387 context_apply_attachment_filter_states(iface, This->render_targets[i], FALSE);
389 if (This->stencilBufferTarget)
390 context_apply_attachment_filter_states(iface, This->stencilBufferTarget, FALSE);
393 for (i = 0; i < GL_LIMITS(buffers); ++i)
395 if (This->render_targets[i])
396 This->draw_buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
397 else
398 This->draw_buffers[i] = GL_NONE;
402 /* GL locking is done by the caller */
403 static void context_apply_fbo_state(IWineD3DDevice *iface)
405 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
406 WineD3DContext *context = This->activeContext;
408 if (This->render_offscreen)
410 context->current_fbo = context_find_fbo_entry(iface, context);
411 context_apply_fbo_entry(iface, context->current_fbo);
412 } else {
413 context->current_fbo = NULL;
414 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
417 context_check_fbo_status(iface);
420 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
422 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
423 UINT i;
425 switch(type)
427 case WINED3DRTYPE_SURFACE:
429 for (i = 0; i < This->numContexts; ++i)
431 WineD3DContext *context = This->contexts[i];
432 struct fbo_entry *entry, *entry2;
434 ENTER_GL();
436 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
438 BOOL destroyed = FALSE;
439 UINT j;
441 for (j = 0; !destroyed && j < GL_LIMITS(buffers); ++j)
443 if (entry->render_targets[j] == (IWineD3DSurface *)resource)
445 context_destroy_fbo_entry(This, context, entry);
446 destroyed = TRUE;
450 if (!destroyed && entry->depth_stencil == (IWineD3DSurface *)resource)
451 context_destroy_fbo_entry(This, context, entry);
454 LEAVE_GL();
457 break;
460 default:
461 break;
465 /*****************************************************************************
466 * Context_MarkStateDirty
468 * Marks a state in a context dirty. Only one context, opposed to
469 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
470 * contexts
472 * Params:
473 * context: Context to mark the state dirty in
474 * state: State to mark dirty
475 * StateTable: Pointer to the state table in use(for state grouping)
477 *****************************************************************************/
478 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
479 DWORD rep = StateTable[state].representative;
480 DWORD idx;
481 BYTE shift;
483 if(!rep || isStateDirty(context, rep)) return;
485 context->dirtyArray[context->numDirtyEntries++] = rep;
486 idx = rep >> 5;
487 shift = rep & 0x1f;
488 context->isStateDirty[idx] |= (1 << shift);
491 /*****************************************************************************
492 * AddContextToArray
494 * Adds a context to the context array. Helper function for CreateContext
496 * This method is not called in performance-critical code paths, only when a
497 * new render target or swapchain is created. Thus performance is not an issue
498 * here.
500 * Params:
501 * This: Device to add the context for
502 * hdc: device context
503 * glCtx: WGL context to add
504 * pbuffer: optional pbuffer used with this context
506 *****************************************************************************/
507 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
508 WineD3DContext **oldArray = This->contexts;
509 DWORD state;
511 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
512 if(This->contexts == NULL) {
513 ERR("Unable to grow the context array\n");
514 This->contexts = oldArray;
515 return NULL;
517 if(oldArray) {
518 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
521 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
522 if(This->contexts[This->numContexts] == NULL) {
523 ERR("Unable to allocate a new context\n");
524 HeapFree(GetProcessHeap(), 0, This->contexts);
525 This->contexts = oldArray;
526 return NULL;
529 This->contexts[This->numContexts]->hdc = hdc;
530 This->contexts[This->numContexts]->glCtx = glCtx;
531 This->contexts[This->numContexts]->pbuffer = pbuffer;
532 This->contexts[This->numContexts]->win_handle = win_handle;
533 HeapFree(GetProcessHeap(), 0, oldArray);
535 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
537 for(state = 0; state <= STATE_HIGHEST; state++) {
538 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
541 This->numContexts++;
542 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
543 return This->contexts[This->numContexts - 1];
546 /* This function takes care of WineD3D pixel format selection. */
547 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
548 const struct GlPixelFormatDesc *color_format_desc, const struct GlPixelFormatDesc *ds_format_desc,
549 BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
551 int iPixelFormat=0;
552 unsigned int matchtry;
553 short redBits, greenBits, blueBits, alphaBits, colorBits;
554 short depthBits=0, stencilBits=0;
556 struct match_type {
557 BOOL require_aux;
558 BOOL exact_alpha;
559 BOOL exact_color;
560 } matches[] = {
561 /* First, try without alpha match buffers. MacOS supports aux buffers only
562 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
563 * Then try without aux buffers - this is the most common cause for not
564 * finding a pixel format. Also some drivers(the open source ones)
565 * only offer 32 bit ARB pixel formats. First try without an exact alpha
566 * match, then try without an exact alpha and color match.
568 { TRUE, TRUE, TRUE },
569 { TRUE, FALSE, TRUE },
570 { FALSE, TRUE, TRUE },
571 { FALSE, FALSE, TRUE },
572 { TRUE, FALSE, FALSE },
573 { FALSE, FALSE, FALSE },
576 int i = 0;
577 int nCfgs = This->adapter->nCfgs;
579 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
580 debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
581 auxBuffers, numSamples, pbuffer, findCompatible);
583 if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
585 ERR("Unable to get color bits for format %s (%#x)!\n",
586 debug_d3dformat(color_format_desc->format), color_format_desc->format);
587 return 0;
590 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
591 * You are able to add a depth + stencil surface at a later stage when you need it.
592 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
593 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
594 * context, need torecreate shaders, textures and other resources.
596 * The context manager already takes care of the state problem and for the other tasks code from Reset
597 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
598 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
599 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
600 * issue needs to be fixed. */
601 if (ds_format_desc->format != WINED3DFMT_D24S8)
603 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
604 ds_format_desc = getFormatDescEntry(WINED3DFMT_D24S8, &This->adapter->gl_info);
607 getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
609 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
610 for(i=0; i<nCfgs; i++) {
611 BOOL exactDepthMatch = TRUE;
612 WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
614 /* For now only accept RGBA formats. Perhaps some day we will
615 * allow floating point formats for pbuffers. */
616 if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
617 continue;
619 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
620 if(!pbuffer && !(cfg->windowDrawable && cfg->doubleBuffer))
621 continue;
623 /* We like to have aux buffers in backbuffer mode */
624 if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
625 continue;
627 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
628 if(pbuffer && (!cfg->pbufferDrawable || cfg->doubleBuffer))
629 continue;
631 if(matches[matchtry].exact_color) {
632 if(cfg->redSize != redBits)
633 continue;
634 if(cfg->greenSize != greenBits)
635 continue;
636 if(cfg->blueSize != blueBits)
637 continue;
638 } else {
639 if(cfg->redSize < redBits)
640 continue;
641 if(cfg->greenSize < greenBits)
642 continue;
643 if(cfg->blueSize < blueBits)
644 continue;
646 if(matches[matchtry].exact_alpha) {
647 if(cfg->alphaSize != alphaBits)
648 continue;
649 } else {
650 if(cfg->alphaSize < alphaBits)
651 continue;
654 /* We try to locate a format which matches our requirements exactly. In case of
655 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
656 if(cfg->depthSize < depthBits)
657 continue;
658 else if(cfg->depthSize > depthBits)
659 exactDepthMatch = FALSE;
661 /* In all cases make sure the number of stencil bits matches our requirements
662 * even when we don't need stencil because it could affect performance EXCEPT
663 * on cards which don't offer depth formats without stencil like the i915 drivers
664 * on Linux. */
665 if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
666 continue;
668 /* Check multisampling support */
669 if(cfg->numSamples != numSamples)
670 continue;
672 /* When we have passed all the checks then we have found a format which matches our
673 * requirements. Note that we only check for a limit number of capabilities right now,
674 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
675 * can still differ in things like multisampling, stereo, SRGB and other flags.
678 /* Exit the loop as we have found a format :) */
679 if(exactDepthMatch) {
680 iPixelFormat = cfg->iPixelFormat;
681 break;
682 } else if(!iPixelFormat) {
683 /* In the end we might end up with a format which doesn't exactly match our depth
684 * requirements. Accept the first format we found because formats with higher iPixelFormat
685 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
686 iPixelFormat = cfg->iPixelFormat;
691 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
692 if(!iPixelFormat && !findCompatible) {
693 ERR("Can't find a suitable iPixelFormat\n");
694 return FALSE;
695 } else if(!iPixelFormat) {
696 PIXELFORMATDESCRIPTOR pfd;
698 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
699 /* PixelFormat selection */
700 ZeroMemory(&pfd, sizeof(pfd));
701 pfd.nSize = sizeof(pfd);
702 pfd.nVersion = 1;
703 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
704 pfd.iPixelType = PFD_TYPE_RGBA;
705 pfd.cAlphaBits = alphaBits;
706 pfd.cColorBits = colorBits;
707 pfd.cDepthBits = depthBits;
708 pfd.cStencilBits = stencilBits;
709 pfd.iLayerType = PFD_MAIN_PLANE;
711 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
712 if(!iPixelFormat) {
713 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
714 ERR("Can't find a suitable iPixelFormat\n");
715 return FALSE;
719 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
720 iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
721 return iPixelFormat;
724 /*****************************************************************************
725 * CreateContext
727 * Creates a new context for a window, or a pbuffer context.
729 * * Params:
730 * This: Device to activate the context for
731 * target: Surface this context will render to
732 * win_handle: handle to the window which we are drawing to
733 * create_pbuffer: tells whether to create a pbuffer or not
734 * pPresentParameters: contains the pixelformats to use for onscreen rendering
736 *****************************************************************************/
737 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
738 HDC oldDrawable, hdc;
739 HPBUFFERARB pbuffer = NULL;
740 HGLRC ctx = NULL, oldCtx;
741 WineD3DContext *ret = NULL;
742 unsigned int s;
744 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
746 if(create_pbuffer) {
747 HDC hdc_parent = GetDC(win_handle);
748 int iPixelFormat = 0;
750 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
751 const struct GlPixelFormatDesc *ds_format_desc = StencilSurface
752 ? ((IWineD3DSurfaceImpl *)StencilSurface)->resource.format_desc
753 : getFormatDescEntry(WINED3DFMT_UNKNOWN, &This->adapter->gl_info);
755 /* Try to find a pixel format with pbuffer support. */
756 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
757 ds_format_desc, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */,
758 FALSE /* findCompatible */);
759 if(!iPixelFormat) {
760 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
762 /* For some reason we weren't able to find a format, try to find something instead of crashing.
763 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
764 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
765 ds_format_desc, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */,
766 TRUE /* findCompatible */);
769 /* This shouldn't happen as ChoosePixelFormat always returns something */
770 if(!iPixelFormat) {
771 ERR("Unable to locate a pixel format for a pbuffer\n");
772 ReleaseDC(win_handle, hdc_parent);
773 goto out;
776 TRACE("Creating a pBuffer drawable for the new context\n");
777 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
778 if(!pbuffer) {
779 ERR("Cannot create a pbuffer\n");
780 ReleaseDC(win_handle, hdc_parent);
781 goto out;
784 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
785 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
786 if(!hdc) {
787 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
788 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
789 ReleaseDC(win_handle, hdc_parent);
790 goto out;
792 ReleaseDC(win_handle, hdc_parent);
793 } else {
794 PIXELFORMATDESCRIPTOR pfd;
795 int iPixelFormat;
796 int res;
797 const struct GlPixelFormatDesc *color_format_desc = target->resource.format_desc;
798 const struct GlPixelFormatDesc *ds_format_desc = getFormatDescEntry(WINED3DFMT_UNKNOWN,
799 &This->adapter->gl_info);
800 BOOL auxBuffers = FALSE;
801 int numSamples = 0;
803 hdc = GetDC(win_handle);
804 if(hdc == NULL) {
805 ERR("Cannot retrieve a device context!\n");
806 goto out;
809 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
810 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
811 auxBuffers = TRUE;
813 if (color_format_desc->format == WINED3DFMT_X4R4G4B4)
814 color_format_desc = getFormatDescEntry(WINED3DFMT_A4R4G4B4, &This->adapter->gl_info);
815 else if (color_format_desc->format == WINED3DFMT_X8R8G8B8)
816 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
819 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
820 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
821 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
822 * a format with 8bit alpha, so request A8R8G8B8. */
823 if (color_format_desc->format == WINED3DFMT_P8)
824 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
826 /* Retrieve the depth stencil format from the present parameters.
827 * The choice of the proper format can give a nice performance boost
828 * in case of GPU limited programs. */
829 if(pPresentParms->EnableAutoDepthStencil) {
830 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
831 ds_format_desc = getFormatDescEntry(pPresentParms->AutoDepthStencilFormat, &This->adapter->gl_info);
834 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
835 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
836 if(!GL_SUPPORT(ARB_MULTISAMPLE))
837 ERR("The program is requesting multisampling without support!\n");
838 else {
839 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
840 numSamples = pPresentParms->MultiSampleType;
844 /* Try to find a pixel format which matches our requirements */
845 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
846 auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
848 /* Try to locate a compatible format if we weren't able to find anything */
849 if(!iPixelFormat) {
850 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
851 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
852 auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
855 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
856 if(!iPixelFormat) {
857 ERR("Can't find a suitable iPixelFormat\n");
858 return FALSE;
861 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
862 res = SetPixelFormat(hdc, iPixelFormat, NULL);
863 if(!res) {
864 int oldPixelFormat = GetPixelFormat(hdc);
866 /* By default WGL doesn't allow pixel format adjustments but we need it here.
867 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
868 * set the pixel format multiple times. Only use it when it is really needed. */
870 if(oldPixelFormat == iPixelFormat) {
871 /* We don't have to do anything as the formats are the same :) */
872 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
873 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
875 if(!res) {
876 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
877 return FALSE;
879 } else if(oldPixelFormat) {
880 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
881 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
882 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
883 } else {
884 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
885 return FALSE;
890 ctx = pwglCreateContext(hdc);
891 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
893 if(!ctx) {
894 ERR("Failed to create a WGL context\n");
895 if(create_pbuffer) {
896 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
897 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
899 goto out;
901 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
902 if(!ret) {
903 ERR("Failed to add the newly created context to the context list\n");
904 pwglDeleteContext(ctx);
905 if(create_pbuffer) {
906 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
907 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
909 goto out;
911 ret->surface = (IWineD3DSurface *) target;
912 ret->isPBuffer = create_pbuffer;
913 ret->tid = GetCurrentThreadId();
914 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
915 /* Create the dirty constants array and initialize them to dirty */
916 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
917 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
918 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
919 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
920 memset(ret->vshader_const_dirty, 1,
921 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
922 memset(ret->pshader_const_dirty, 1,
923 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
926 TRACE("Successfully created new context %p\n", ret);
928 list_init(&ret->fbo_list);
930 /* Set up the context defaults */
931 oldCtx = pwglGetCurrentContext();
932 oldDrawable = pwglGetCurrentDC();
933 if(oldCtx && oldDrawable) {
934 /* See comment in ActivateContext context switching */
935 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
937 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
938 ERR("Cannot activate context to set up defaults\n");
939 goto out;
942 ENTER_GL();
944 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
946 TRACE("Setting up the screen\n");
947 /* Clear the screen */
948 glClearColor(1.0, 0.0, 0.0, 0.0);
949 checkGLcall("glClearColor");
950 glClearIndex(0);
951 glClearDepth(1);
952 glClearStencil(0xffff);
954 checkGLcall("glClear");
956 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
957 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
959 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
960 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
962 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
963 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
965 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
966 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
967 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
968 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
970 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
971 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
972 * and textures in DIB sections(due to the memory protection).
974 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
975 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
977 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
978 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
979 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
980 * GL_VERTEX_BLEND_ARB isn't enabled too
982 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
983 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
985 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
986 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
987 * the previous texture where to source the offset from is always unit - 1.
989 for(s = 1; s < GL_LIMITS(textures); s++) {
990 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
991 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
992 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
995 if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
996 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
997 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
998 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
999 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1000 * is ever assigned.
1002 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1003 * program and the dummy program is destroyed when the context is destroyed.
1005 const char *dummy_program =
1006 "!!ARBfp1.0\n"
1007 "MOV result.color, fragment.color.primary;\n"
1008 "END\n";
1009 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1010 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1011 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1014 for(s = 0; s < GL_LIMITS(point_sprite_units); s++) {
1015 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1016 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1017 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
1019 LEAVE_GL();
1021 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
1022 * but enable it for the first context we create, and reenable it on the old context
1024 if(oldDrawable && oldCtx) {
1025 pwglMakeCurrent(oldDrawable, oldCtx);
1026 } else {
1027 last_device = This;
1029 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1031 return ret;
1033 out:
1034 return NULL;
1037 /*****************************************************************************
1038 * RemoveContextFromArray
1040 * Removes a context from the context manager. The opengl context is not
1041 * destroyed or unset. context is not a valid pointer after that call.
1043 * Similar to the former call this isn't a performance critical function. A
1044 * helper function for DestroyContext.
1046 * Params:
1047 * This: Device to activate the context for
1048 * context: Context to remove
1050 *****************************************************************************/
1051 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
1052 WineD3DContext **new_array;
1053 BOOL found = FALSE;
1054 UINT i;
1056 TRACE("Removing ctx %p\n", context);
1058 for (i = 0; i < This->numContexts; ++i)
1060 if (This->contexts[i] == context)
1062 HeapFree(GetProcessHeap(), 0, context);
1063 found = TRUE;
1064 break;
1068 if (!found)
1070 ERR("Context %p doesn't exist in context array\n", context);
1071 return;
1074 while (i < This->numContexts - 1)
1076 This->contexts[i] = This->contexts[i + 1];
1077 ++i;
1080 --This->numContexts;
1081 if (!This->numContexts)
1083 HeapFree(GetProcessHeap(), 0, This->contexts);
1084 This->contexts = NULL;
1085 return;
1088 new_array = HeapReAlloc(GetProcessHeap(), 0, This->contexts, This->numContexts * sizeof(*This->contexts));
1089 if (!new_array)
1091 ERR("Failed to shrink context array. Oh well.\n");
1092 return;
1095 This->contexts = new_array;
1098 /*****************************************************************************
1099 * DestroyContext
1101 * Destroys a wineD3DContext
1103 * Params:
1104 * This: Device to activate the context for
1105 * context: Context to destroy
1107 *****************************************************************************/
1108 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
1109 struct fbo_entry *entry, *entry2;
1111 TRACE("Destroying ctx %p\n", context);
1113 /* The correct GL context needs to be active to cleanup the GL resources below */
1114 if(pwglGetCurrentContext() != context->glCtx){
1115 pwglMakeCurrent(context->hdc, context->glCtx);
1116 last_device = NULL;
1119 ENTER_GL();
1121 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
1122 context_destroy_fbo_entry(This, context, entry);
1124 if (context->src_fbo) {
1125 TRACE("Destroy src FBO %d\n", context->src_fbo);
1126 context_destroy_fbo(This, &context->src_fbo);
1128 if (context->dst_fbo) {
1129 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
1130 context_destroy_fbo(This, &context->dst_fbo);
1132 if(context->dummy_arbfp_prog) {
1133 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1136 LEAVE_GL();
1138 if (This->activeContext == context)
1140 This->activeContext = NULL;
1141 TRACE("Destroying the active context.\n");
1144 /* Cleanup the GL context */
1145 pwglMakeCurrent(NULL, NULL);
1146 if(context->isPBuffer) {
1147 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
1148 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
1149 } else ReleaseDC(context->win_handle, context->hdc);
1150 pwglDeleteContext(context->glCtx);
1152 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1153 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1154 RemoveContextFromArray(This, context);
1157 /* GL locking is done by the caller */
1158 static inline void set_blit_dimension(UINT width, UINT height) {
1159 glMatrixMode(GL_PROJECTION);
1160 checkGLcall("glMatrixMode(GL_PROJECTION)");
1161 glLoadIdentity();
1162 checkGLcall("glLoadIdentity()");
1163 glOrtho(0, width, height, 0, 0.0, -1.0);
1164 checkGLcall("glOrtho");
1165 glViewport(0, 0, width, height);
1166 checkGLcall("glViewport");
1169 /*****************************************************************************
1170 * SetupForBlit
1172 * Sets up a context for DirectDraw blitting.
1173 * All texture units are disabled, texture unit 0 is set as current unit
1174 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1175 * color writing enabled for all channels
1176 * register combiners disabled, shaders disabled
1177 * world matrix is set to identity, texture matrix 0 too
1178 * projection matrix is setup for drawing screen coordinates
1180 * Params:
1181 * This: Device to activate the context for
1182 * context: Context to setup
1183 * width: render target width
1184 * height: render target height
1186 *****************************************************************************/
1187 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
1188 int i, sampler;
1189 const struct StateEntry *StateTable = This->StateTable;
1191 TRACE("Setting up context %p for blitting\n", context);
1192 if(context->last_was_blit) {
1193 if(context->blit_w != width || context->blit_h != height) {
1194 ENTER_GL();
1195 set_blit_dimension(width, height);
1196 LEAVE_GL();
1197 context->blit_w = width; context->blit_h = height;
1198 /* No need to dirtify here, the states are still dirtified because they weren't
1199 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1200 * be set
1203 TRACE("Context is already set up for blitting, nothing to do\n");
1204 return;
1206 context->last_was_blit = TRUE;
1208 /* TODO: Use a display list */
1210 /* Disable shaders */
1211 ENTER_GL();
1212 This->shader_backend->shader_select((IWineD3DDevice *)This, FALSE, FALSE);
1213 LEAVE_GL();
1215 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1216 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1218 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1219 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1220 * which can safely be called from here, we only lock once instead locking/unlocking
1221 * after each GL call.
1223 ENTER_GL();
1225 /* Disable all textures. The caller can then bind a texture it wants to blit
1226 * from
1228 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1229 * function texture unit. No need to care for higher samplers
1231 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
1232 sampler = This->rev_tex_unit_map[i];
1233 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1234 checkGLcall("glActiveTextureARB");
1236 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1237 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1238 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1240 glDisable(GL_TEXTURE_3D);
1241 checkGLcall("glDisable GL_TEXTURE_3D");
1242 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1243 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1244 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1246 glDisable(GL_TEXTURE_2D);
1247 checkGLcall("glDisable GL_TEXTURE_2D");
1249 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1250 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1252 if (sampler != -1) {
1253 if (sampler < MAX_TEXTURES) {
1254 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1256 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1259 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1260 checkGLcall("glActiveTextureARB");
1262 sampler = This->rev_tex_unit_map[0];
1264 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1265 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1266 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1268 glDisable(GL_TEXTURE_3D);
1269 checkGLcall("glDisable GL_TEXTURE_3D");
1270 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1271 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1272 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1274 glDisable(GL_TEXTURE_2D);
1275 checkGLcall("glDisable GL_TEXTURE_2D");
1277 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1279 glMatrixMode(GL_TEXTURE);
1280 checkGLcall("glMatrixMode(GL_TEXTURE)");
1281 glLoadIdentity();
1282 checkGLcall("glLoadIdentity()");
1284 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
1285 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1286 GL_TEXTURE_LOD_BIAS_EXT,
1287 0.0);
1288 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1291 if (sampler != -1) {
1292 if (sampler < MAX_TEXTURES) {
1293 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1294 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1296 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1299 /* Other misc states */
1300 glDisable(GL_ALPHA_TEST);
1301 checkGLcall("glDisable(GL_ALPHA_TEST)");
1302 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1303 glDisable(GL_LIGHTING);
1304 checkGLcall("glDisable GL_LIGHTING");
1305 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1306 glDisable(GL_DEPTH_TEST);
1307 checkGLcall("glDisable GL_DEPTH_TEST");
1308 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1309 glDisableWINE(GL_FOG);
1310 checkGLcall("glDisable GL_FOG");
1311 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1312 glDisable(GL_BLEND);
1313 checkGLcall("glDisable GL_BLEND");
1314 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1315 glDisable(GL_CULL_FACE);
1316 checkGLcall("glDisable GL_CULL_FACE");
1317 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1318 glDisable(GL_STENCIL_TEST);
1319 checkGLcall("glDisable GL_STENCIL_TEST");
1320 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1321 glDisable(GL_SCISSOR_TEST);
1322 checkGLcall("glDisable GL_SCISSOR_TEST");
1323 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1324 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
1325 glDisable(GL_POINT_SPRITE_ARB);
1326 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1327 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1329 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1330 checkGLcall("glColorMask");
1331 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1332 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
1333 glDisable(GL_COLOR_SUM_EXT);
1334 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1335 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1338 /* Setup transforms */
1339 glMatrixMode(GL_MODELVIEW);
1340 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1341 glLoadIdentity();
1342 checkGLcall("glLoadIdentity()");
1343 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1345 context->last_was_rhw = TRUE;
1346 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1348 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1349 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1350 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1351 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1352 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1353 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1354 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1356 set_blit_dimension(width, height);
1358 LEAVE_GL();
1360 context->blit_w = width; context->blit_h = height;
1361 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1362 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1365 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1368 /*****************************************************************************
1369 * findThreadContextForSwapChain
1371 * Searches a swapchain for all contexts and picks one for the thread tid.
1372 * If none can be found the swapchain is requested to create a new context
1374 *****************************************************************************/
1375 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
1376 unsigned int i;
1378 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1379 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1380 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1385 /* Create a new context for the thread */
1386 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
1389 /*****************************************************************************
1390 * FindContext
1392 * Finds a context for the current render target and thread
1394 * Parameters:
1395 * target: Render target to find the context for
1396 * tid: Thread to activate the context for
1398 * Returns: The needed context
1400 *****************************************************************************/
1401 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
1402 IWineD3DSwapChain *swapchain = NULL;
1403 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
1404 WineD3DContext *context = This->activeContext;
1405 BOOL oldRenderOffscreen = This->render_offscreen;
1406 const struct GlPixelFormatDesc *old = ((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->resource.format_desc;
1407 const struct GlPixelFormatDesc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
1408 const struct StateEntry *StateTable = This->StateTable;
1410 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1411 * the alpha blend state changes with different render target formats
1413 if (old->format != new->format)
1415 /* Disable blending when the alpha mask has changed and when a format doesn't support blending */
1416 if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
1417 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
1419 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1423 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1424 TRACE("Rendering onscreen\n");
1426 context = findThreadContextForSwapChain(swapchain, tid);
1428 This->render_offscreen = FALSE;
1429 /* The context != This->activeContext will catch a NOP context change. This can occur
1430 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1431 * rendering. No context change is needed in that case
1434 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1435 if(This->pbufferContext && tid == This->pbufferContext->tid) {
1436 This->pbufferContext->tid = 0;
1439 IWineD3DSwapChain_Release(swapchain);
1441 if(oldRenderOffscreen) {
1442 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1443 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1444 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1445 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1446 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1449 } else {
1450 TRACE("Rendering offscreen\n");
1451 This->render_offscreen = TRUE;
1453 switch(wined3d_settings.offscreen_rendering_mode) {
1454 case ORM_FBO:
1455 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1456 if(This->activeContext && tid == This->lastThread) {
1457 context = This->activeContext;
1458 } else {
1459 /* This may happen if the app jumps straight into offscreen rendering
1460 * Start using the context of the primary swapchain. tid == 0 is no problem
1461 * for findThreadContextForSwapChain.
1463 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1464 * is perfect to call.
1466 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1468 break;
1470 case ORM_PBUFFER:
1472 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
1473 if(This->pbufferContext == NULL ||
1474 This->pbufferWidth < targetimpl->currentDesc.Width ||
1475 This->pbufferHeight < targetimpl->currentDesc.Height) {
1476 if(This->pbufferContext) {
1477 DestroyContext(This, This->pbufferContext);
1480 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1481 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1483 This->pbufferContext = CreateContext(This, targetimpl,
1484 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1485 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1486 This->pbufferWidth = targetimpl->currentDesc.Width;
1487 This->pbufferHeight = targetimpl->currentDesc.Height;
1490 if(This->pbufferContext) {
1491 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1492 FIXME("The PBuffr context is only supported for one thread for now!\n");
1494 This->pbufferContext->tid = tid;
1495 context = This->pbufferContext;
1496 break;
1497 } else {
1498 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1499 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1503 case ORM_BACKBUFFER:
1504 /* Stay with the currently active context for back buffer rendering */
1505 if(This->activeContext && tid == This->lastThread) {
1506 context = This->activeContext;
1507 } else {
1508 /* This may happen if the app jumps straight into offscreen rendering
1509 * Start using the context of the primary swapchain. tid == 0 is no problem
1510 * for findThreadContextForSwapChain.
1512 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1513 * is perfect to call.
1515 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1517 break;
1520 if(!oldRenderOffscreen) {
1521 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1522 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1523 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1524 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1525 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1529 /* When switching away from an offscreen render target, and we're not using FBOs,
1530 * we have to read the drawable into the texture. This is done via PreLoad(and
1531 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1532 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1533 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1534 * is read. This leads to these possible situations:
1536 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1537 * Nothing to do, we don't even reach this code in this case...
1539 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1540 * The currently active context is OK for readback. Call PreLoad, and it
1541 * performs the read
1543 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1544 * Nothing to do - the drawable is unchanged
1546 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1547 * This is tricky. We have to get a context with the old drawable from somewhere
1548 * before we can switch to the new context. In this case, PreLoad calls
1549 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1550 * is case (2) then. The old drawable is activated for the new thread, and the
1551 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1552 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1553 * target for the new thread
1555 if (readTexture && This->lastActiveRenderTarget != target) {
1556 BOOL oldInDraw = This->isInDraw;
1558 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1559 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1560 * when using offscreen rendering with multithreading
1562 This->isInDraw = TRUE;
1564 /* Do that before switching the context:
1565 * Read the back buffer of the old drawable into the destination texture
1567 if(((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->glDescription.srgbTextureName) {
1568 surface_internal_preload(This->lastActiveRenderTarget, SRGB_BOTH);
1569 } else {
1570 surface_internal_preload(This->lastActiveRenderTarget, SRGB_RGB);
1573 /* Assume that the drawable will be modified by some other things now */
1574 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1576 This->isInDraw = oldInDraw;
1579 return context;
1582 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1584 IWineD3DSwapChain *swapchain;
1586 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain)))
1588 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1589 ENTER_GL();
1590 glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1591 checkGLcall("glDrawBuffers()");
1592 LEAVE_GL();
1594 else
1596 ENTER_GL();
1597 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1599 if (!blit)
1601 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1603 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1604 checkGLcall("glDrawBuffers()");
1606 else
1608 glDrawBuffer(This->draw_buffers[0]);
1609 checkGLcall("glDrawBuffer()");
1611 } else {
1612 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1613 checkGLcall("glDrawBuffer()");
1616 else
1618 glDrawBuffer(This->offscreenBuffer);
1619 checkGLcall("glDrawBuffer()");
1621 LEAVE_GL();
1625 /*****************************************************************************
1626 * ActivateContext
1628 * Finds a rendering context and drawable matching the device and render
1629 * target for the current thread, activates them and puts them into the
1630 * requested state.
1632 * Params:
1633 * This: Device to activate the context for
1634 * target: Requested render target
1635 * usage: Prepares the context for blitting, drawing or other actions
1637 *****************************************************************************/
1638 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1639 DWORD tid = GetCurrentThreadId();
1640 DWORD i, dirtyState, idx;
1641 BYTE shift;
1642 WineD3DContext *context;
1643 const struct StateEntry *StateTable = This->StateTable;
1645 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1646 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1647 context = FindContext(This, target, tid);
1648 context->draw_buffer_dirty = TRUE;
1649 This->lastActiveRenderTarget = target;
1650 This->lastThread = tid;
1651 } else {
1652 /* Stick to the old context */
1653 context = This->activeContext;
1656 /* Activate the opengl context */
1657 if(last_device != This || context != This->activeContext) {
1658 BOOL ret;
1660 /* Prevent an unneeded context switch as those are expensive */
1661 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1662 TRACE("Already using gl context %p\n", context->glCtx);
1664 else {
1665 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1667 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1668 if(ret == FALSE) {
1669 ERR("Failed to activate the new context\n");
1670 } else if(!context->last_was_blit) {
1671 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1672 } else {
1673 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1676 if(This->activeContext->vshader_const_dirty) {
1677 memset(This->activeContext->vshader_const_dirty, 1,
1678 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1680 if(This->activeContext->pshader_const_dirty) {
1681 memset(This->activeContext->pshader_const_dirty, 1,
1682 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1684 This->activeContext = context;
1685 last_device = This;
1688 switch (usage) {
1689 case CTXUSAGE_CLEAR:
1690 case CTXUSAGE_DRAWPRIM:
1691 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1692 ENTER_GL();
1693 context_apply_fbo_state((IWineD3DDevice *)This);
1694 LEAVE_GL();
1696 if (context->draw_buffer_dirty) {
1697 apply_draw_buffer(This, target, FALSE);
1698 context->draw_buffer_dirty = FALSE;
1700 break;
1702 case CTXUSAGE_BLIT:
1703 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1704 if (This->render_offscreen) {
1705 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1706 ENTER_GL();
1707 context_bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1708 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1709 context_attach_depth_stencil_fbo(This, GL_FRAMEBUFFER_EXT, NULL, FALSE);
1710 LEAVE_GL();
1711 } else {
1712 ENTER_GL();
1713 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1714 checkGLcall("glFramebufferRenderbufferEXT");
1715 LEAVE_GL();
1717 context->draw_buffer_dirty = TRUE;
1719 if (context->draw_buffer_dirty) {
1720 apply_draw_buffer(This, target, TRUE);
1721 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1722 context->draw_buffer_dirty = FALSE;
1725 break;
1727 default:
1728 break;
1731 switch(usage) {
1732 case CTXUSAGE_RESOURCELOAD:
1733 /* This does not require any special states to be set up */
1734 break;
1736 case CTXUSAGE_CLEAR:
1737 if(context->last_was_blit) {
1738 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1741 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1742 * blending when clearing improves the clearing performance incredibly.
1744 ENTER_GL();
1745 glDisable(GL_BLEND);
1746 LEAVE_GL();
1747 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1749 ENTER_GL();
1750 glEnable(GL_SCISSOR_TEST);
1751 checkGLcall("glEnable GL_SCISSOR_TEST");
1752 LEAVE_GL();
1753 context->last_was_blit = FALSE;
1754 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1755 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1756 break;
1758 case CTXUSAGE_DRAWPRIM:
1759 /* This needs all dirty states applied */
1760 if(context->last_was_blit) {
1761 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1764 IWineD3DDeviceImpl_FindTexUnitMap(This);
1766 ENTER_GL();
1767 for(i=0; i < context->numDirtyEntries; i++) {
1768 dirtyState = context->dirtyArray[i];
1769 idx = dirtyState >> 5;
1770 shift = dirtyState & 0x1f;
1771 context->isStateDirty[idx] &= ~(1 << shift);
1772 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1774 LEAVE_GL();
1775 context->numDirtyEntries = 0; /* This makes the whole list clean */
1776 context->last_was_blit = FALSE;
1777 break;
1779 case CTXUSAGE_BLIT:
1780 SetupForBlit(This, context,
1781 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1782 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1783 break;
1785 default:
1786 FIXME("Unexpected context usage requested\n");
1790 WineD3DContext *getActiveContext(void) {
1791 return last_device->activeContext;