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
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 void context_bind_fbo(IWineD3DDevice *iface, GLenum target, GLuint *fbo)
43 const IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
47 GL_EXTCALL(glGenFramebuffersEXT(1, fbo));
48 checkGLcall("glGenFramebuffersEXT()");
49 TRACE("Created FBO %d\n", *fbo);
52 GL_EXTCALL(glBindFramebufferEXT(target, *fbo));
53 checkGLcall("glBindFramebuffer()");
56 static void context_destroy_fbo(IWineD3DDeviceImpl *This, const GLuint *fbo)
60 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, *fbo));
61 checkGLcall("glBindFramebuffer()");
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()");
69 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
70 checkGLcall("glBindFramebuffer()");
71 GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo));
72 checkGLcall("glDeleteFramebuffers()");
75 static void context_apply_attachment_filter_states(IWineD3DDevice *iface, IWineD3DSurface *surface, BOOL force_preload)
77 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
78 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
79 IWineD3DBaseTextureImpl *texture_impl;
80 BOOL update_minfilter = FALSE;
81 BOOL update_magfilter = FALSE;
83 /* Update base texture states array */
84 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
86 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT)
88 texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
89 update_minfilter = TRUE;
92 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
94 texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
95 update_magfilter = TRUE;
98 if (texture_impl->baseTexture.bindCount)
100 WARN("Render targets should not be bound to a sampler\n");
101 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(texture_impl->baseTexture.sampler));
104 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
107 if (update_minfilter || update_magfilter || force_preload)
109 GLenum target, bind_target;
112 target = surface_impl->glDescription.target;
113 if (target == GL_TEXTURE_2D)
115 bind_target = GL_TEXTURE_2D;
116 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
117 } else if (target == GL_TEXTURE_RECTANGLE_ARB) {
118 bind_target = GL_TEXTURE_RECTANGLE_ARB;
119 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
121 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
122 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
125 IWineD3DSurface_PreLoad(surface);
127 glBindTexture(bind_target, surface_impl->glDescription.textureName);
128 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
129 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
130 glBindTexture(bind_target, old_binding);
133 checkGLcall("apply_attachment_filter_states()");
136 /* TODO: Handle stencil attachments */
137 void context_attach_depth_stencil_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
139 IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
141 TRACE("Attach depth stencil %p\n", depth_stencil);
145 if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
147 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
148 checkGLcall("glFramebufferRenderbufferEXT()");
150 context_apply_attachment_filter_states((IWineD3DDevice *)This, depth_stencil, TRUE);
152 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, depth_stencil_impl->glDescription.target,
153 depth_stencil_impl->glDescription.textureName, depth_stencil_impl->glDescription.level));
154 checkGLcall("glFramebufferTexture2DEXT()");
157 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
158 checkGLcall("glFramebufferTexture2DEXT()");
162 void context_attach_surface_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
164 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
166 TRACE("Attach surface %p to %u\n", surface, idx);
170 context_apply_attachment_filter_states((IWineD3DDevice *)This, surface, TRUE);
172 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, surface_impl->glDescription.target,
173 surface_impl->glDescription.textureName, surface_impl->glDescription.level));
174 checkGLcall("glFramebufferTexture2DEXT()");
176 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, GL_TEXTURE_2D, 0, 0));
177 checkGLcall("glFramebufferTexture2DEXT()");
181 static void context_check_fbo_status(IWineD3DDevice *iface)
183 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
186 status = GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
187 if (status == GL_FRAMEBUFFER_COMPLETE_EXT)
189 TRACE("FBO complete\n");
191 IWineD3DSurfaceImpl *attachment;
193 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
195 /* Dump the FBO attachments */
196 for (i = 0; i < GL_LIMITS(buffers); ++i)
198 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->render_targets[i];
201 FIXME("\tColor attachment %d: (%p) %s %ux%u\n", i, attachment, debug_d3dformat(attachment->resource.format),
202 attachment->pow2Width, attachment->pow2Height);
205 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->depth_stencil;
208 FIXME("\tDepth attachment: (%p) %s %ux%u\n", attachment, debug_d3dformat(attachment->resource.format),
209 attachment->pow2Width, attachment->pow2Height);
214 static struct fbo_entry *context_create_fbo_entry(IWineD3DDevice *iface)
216 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
217 struct fbo_entry *entry;
219 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
220 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
221 memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
222 entry->depth_stencil = This->stencilBufferTarget;
223 entry->attached = FALSE;
229 static void context_destroy_fbo_entry(IWineD3DDeviceImpl *This, struct fbo_entry *entry)
233 TRACE("Destroy FBO %d\n", entry->id);
234 context_destroy_fbo(This, &entry->id);
236 list_remove(&entry->entry);
237 HeapFree(GetProcessHeap(), 0, entry->render_targets);
238 HeapFree(GetProcessHeap(), 0, entry);
242 static struct fbo_entry *context_find_fbo_entry(IWineD3DDevice *iface, WineD3DContext *context)
244 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
245 struct fbo_entry *entry;
247 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
249 if (!memcmp(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets))
250 && entry->depth_stencil == This->stencilBufferTarget)
256 entry = context_create_fbo_entry(iface);
257 list_add_head(&context->fbo_list, &entry->entry);
261 static void context_apply_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
263 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
266 context_bind_fbo(iface, GL_FRAMEBUFFER_EXT, &entry->id);
268 if (!entry->attached)
270 /* Apply render targets */
271 for (i = 0; i < GL_LIMITS(buffers); ++i)
273 IWineD3DSurface *render_target = This->render_targets[i];
274 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, i, render_target);
277 /* Apply depth targets */
278 if (This->stencilBufferTarget) {
279 unsigned int w = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Width;
280 unsigned int h = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Height;
282 surface_set_compatible_renderbuffer(This->stencilBufferTarget, w, h);
284 context_attach_depth_stencil_fbo(This, GL_FRAMEBUFFER_EXT, This->stencilBufferTarget, TRUE);
286 entry->attached = TRUE;
288 for (i = 0; i < GL_LIMITS(buffers); ++i)
290 if (This->render_targets[i])
291 context_apply_attachment_filter_states(iface, This->render_targets[i], FALSE);
293 if (This->stencilBufferTarget)
294 context_apply_attachment_filter_states(iface, This->stencilBufferTarget, FALSE);
297 for (i = 0; i < GL_LIMITS(buffers); ++i)
299 if (This->render_targets[i])
300 This->draw_buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
302 This->draw_buffers[i] = GL_NONE;
306 static void context_apply_fbo_state(IWineD3DDevice *iface)
308 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
309 WineD3DContext *context = This->activeContext;
311 if (This->render_offscreen)
313 context->current_fbo = context_find_fbo_entry(iface, context);
314 context_apply_fbo_entry(iface, context->current_fbo);
316 context->current_fbo = NULL;
317 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
320 context_check_fbo_status(iface);
323 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
325 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
330 case WINED3DRTYPE_SURFACE:
332 for (i = 0; i < This->numContexts; ++i)
334 struct fbo_entry *entry, *entry2;
336 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->contexts[i]->fbo_list, struct fbo_entry, entry)
338 BOOL destroyed = FALSE;
341 for (j = 0; !destroyed && j < GL_LIMITS(buffers); ++j)
343 if (entry->render_targets[j] == (IWineD3DSurface *)resource)
345 context_destroy_fbo_entry(This, entry);
350 if (!destroyed && entry->depth_stencil == (IWineD3DSurface *)resource)
351 context_destroy_fbo_entry(This, entry);
363 /*****************************************************************************
364 * Context_MarkStateDirty
366 * Marks a state in a context dirty. Only one context, opposed to
367 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
371 * context: Context to mark the state dirty in
372 * state: State to mark dirty
373 * StateTable: Pointer to the state table in use(for state grouping)
375 *****************************************************************************/
376 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
377 DWORD rep = StateTable[state].representative;
381 if(!rep || isStateDirty(context, rep)) return;
383 context->dirtyArray[context->numDirtyEntries++] = rep;
386 context->isStateDirty[idx] |= (1 << shift);
389 /*****************************************************************************
392 * Adds a context to the context array. Helper function for CreateContext
394 * This method is not called in performance-critical code paths, only when a
395 * new render target or swapchain is created. Thus performance is not an issue
399 * This: Device to add the context for
400 * hdc: device context
401 * glCtx: WGL context to add
402 * pbuffer: optional pbuffer used with this context
404 *****************************************************************************/
405 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
406 WineD3DContext **oldArray = This->contexts;
409 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
410 if(This->contexts == NULL) {
411 ERR("Unable to grow the context array\n");
412 This->contexts = oldArray;
416 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
419 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
420 if(This->contexts[This->numContexts] == NULL) {
421 ERR("Unable to allocate a new context\n");
422 HeapFree(GetProcessHeap(), 0, This->contexts);
423 This->contexts = oldArray;
427 This->contexts[This->numContexts]->hdc = hdc;
428 This->contexts[This->numContexts]->glCtx = glCtx;
429 This->contexts[This->numContexts]->pbuffer = pbuffer;
430 This->contexts[This->numContexts]->win_handle = win_handle;
431 HeapFree(GetProcessHeap(), 0, oldArray);
433 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
435 for(state = 0; state <= STATE_HIGHEST; state++) {
436 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
440 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
441 return This->contexts[This->numContexts - 1];
444 /* This function takes care of WineD3D pixel format selection. */
445 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc, WINED3DFORMAT ColorFormat, WINED3DFORMAT DepthStencilFormat, BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
447 int iPixelFormat=0, matchtry;
448 short redBits, greenBits, blueBits, alphaBits, colorBits;
449 short depthBits=0, stencilBits=0;
456 /* First, try without alpha match buffers. MacOS supports aux buffers only
457 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
458 * Then try without aux buffers - this is the most common cause for not
459 * finding a pixel format. Also some drivers(the open source ones)
460 * only offer 32 bit ARB pixel formats. First try without an exact alpha
461 * match, then try without an exact alpha and color match.
463 { TRUE, TRUE, TRUE },
464 { TRUE, FALSE, TRUE },
465 { FALSE, TRUE, TRUE },
466 { FALSE, FALSE, TRUE },
467 { TRUE, FALSE, FALSE },
468 { FALSE, FALSE, FALSE },
472 int nCfgs = This->adapter->nCfgs;
473 WineD3D_PixelFormat *cfgs = This->adapter->cfgs;
475 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
476 debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat), auxBuffers, numSamples, pbuffer, findCompatible);
478 if(!getColorBits(ColorFormat, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
479 ERR("Unable to get color bits for format %s (%#x)!\n", debug_d3dformat(ColorFormat), ColorFormat);
483 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
484 * You are able to add a depth + stencil surface at a later stage when you need it.
485 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
486 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
487 * context, need torecreate shaders, textures and other resources.
489 * The context manager already takes care of the state problem and for the other tasks code from Reset
490 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
491 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
492 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
493 * issue needs to be fixed. */
494 if(DepthStencilFormat != WINED3DFMT_D24S8)
495 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
497 DepthStencilFormat = WINED3DFMT_D24S8;
499 if(DepthStencilFormat) {
500 getDepthStencilBits(DepthStencilFormat, &depthBits, &stencilBits);
503 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
504 for(i=0; i<nCfgs; i++) {
505 BOOL exactDepthMatch = TRUE;
506 cfgs = &This->adapter->cfgs[i];
508 /* For now only accept RGBA formats. Perhaps some day we will
509 * allow floating point formats for pbuffers. */
510 if(cfgs->iPixelType != WGL_TYPE_RGBA_ARB)
513 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
514 if(!pbuffer && !(cfgs->windowDrawable && cfgs->doubleBuffer))
517 /* We like to have aux buffers in backbuffer mode */
518 if(auxBuffers && !cfgs->auxBuffers && matches[matchtry].require_aux)
521 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
522 if(pbuffer && (!cfgs->pbufferDrawable || cfgs->doubleBuffer))
525 if(matches[matchtry].exact_color) {
526 if(cfgs->redSize != redBits)
528 if(cfgs->greenSize != greenBits)
530 if(cfgs->blueSize != blueBits)
533 if(cfgs->redSize < redBits)
535 if(cfgs->greenSize < greenBits)
537 if(cfgs->blueSize < blueBits)
540 if(matches[matchtry].exact_alpha) {
541 if(cfgs->alphaSize != alphaBits)
544 if(cfgs->alphaSize < alphaBits)
548 /* We try to locate a format which matches our requirements exactly. In case of
549 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
550 if(cfgs->depthSize < depthBits)
552 else if(cfgs->depthSize > depthBits)
553 exactDepthMatch = FALSE;
555 /* In all cases make sure the number of stencil bits matches our requirements
556 * even when we don't need stencil because it could affect performance EXCEPT
557 * on cards which don't offer depth formats without stencil like the i915 drivers
559 if(stencilBits != cfgs->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfgs->stencilSize))
562 /* Check multisampling support */
563 if(cfgs->numSamples != numSamples)
566 /* When we have passed all the checks then we have found a format which matches our
567 * requirements. Note that we only check for a limit number of capabilities right now,
568 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
569 * can still differ in things like multisampling, stereo, SRGB and other flags.
572 /* Exit the loop as we have found a format :) */
573 if(exactDepthMatch) {
574 iPixelFormat = cfgs->iPixelFormat;
576 } else if(!iPixelFormat) {
577 /* In the end we might end up with a format which doesn't exactly match our depth
578 * requirements. Accept the first format we found because formats with higher iPixelFormat
579 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
580 iPixelFormat = cfgs->iPixelFormat;
585 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
586 if(!iPixelFormat && !findCompatible) {
587 ERR("Can't find a suitable iPixelFormat\n");
589 } else if(!iPixelFormat) {
590 PIXELFORMATDESCRIPTOR pfd;
592 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
593 /* PixelFormat selection */
594 ZeroMemory(&pfd, sizeof(pfd));
595 pfd.nSize = sizeof(pfd);
597 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
598 pfd.iPixelType = PFD_TYPE_RGBA;
599 pfd.cAlphaBits = alphaBits;
600 pfd.cColorBits = colorBits;
601 pfd.cDepthBits = depthBits;
602 pfd.cStencilBits = stencilBits;
603 pfd.iLayerType = PFD_MAIN_PLANE;
605 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
607 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
608 ERR("Can't find a suitable iPixelFormat\n");
613 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n", iPixelFormat, debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat));
617 /*****************************************************************************
620 * Creates a new context for a window, or a pbuffer context.
623 * This: Device to activate the context for
624 * target: Surface this context will render to
625 * win_handle: handle to the window which we are drawing to
626 * create_pbuffer: tells whether to create a pbuffer or not
627 * pPresentParameters: contains the pixelformats to use for onscreen rendering
629 *****************************************************************************/
630 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
631 HDC oldDrawable, hdc;
632 HPBUFFERARB pbuffer = NULL;
633 HGLRC ctx = NULL, oldCtx;
634 WineD3DContext *ret = NULL;
637 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
640 HDC hdc_parent = GetDC(win_handle);
641 int iPixelFormat = 0;
643 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
644 WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
646 /* Try to find a pixel format with pbuffer support. */
647 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */, FALSE /* findCompatible */);
649 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
651 /* For some reason we weren't able to find a format, try to find something instead of crashing.
652 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
653 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */, TRUE /* findCompatible */);
656 /* This shouldn't happen as ChoosePixelFormat always returns something */
658 ERR("Unable to locate a pixel format for a pbuffer\n");
659 ReleaseDC(win_handle, hdc_parent);
663 TRACE("Creating a pBuffer drawable for the new context\n");
664 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
666 ERR("Cannot create a pbuffer\n");
667 ReleaseDC(win_handle, hdc_parent);
671 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
672 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
674 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
675 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
676 ReleaseDC(win_handle, hdc_parent);
679 ReleaseDC(win_handle, hdc_parent);
681 PIXELFORMATDESCRIPTOR pfd;
684 WINED3DFORMAT ColorFormat = target->resource.format;
685 WINED3DFORMAT DepthStencilFormat = 0;
686 BOOL auxBuffers = FALSE;
689 hdc = GetDC(win_handle);
691 ERR("Cannot retrieve a device context!\n");
695 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
696 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
699 if(target->resource.format == WINED3DFMT_X4R4G4B4)
700 ColorFormat = WINED3DFMT_A4R4G4B4;
701 else if(target->resource.format == WINED3DFMT_X8R8G8B8)
702 ColorFormat = WINED3DFMT_A8R8G8B8;
705 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
706 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
707 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
708 * a format with 8bit alpha, so request A8R8G8B8. */
709 if(ColorFormat == WINED3DFMT_P8)
710 ColorFormat = WINED3DFMT_A8R8G8B8;
712 /* Retrieve the depth stencil format from the present parameters.
713 * The choice of the proper format can give a nice performance boost
714 * in case of GPU limited programs. */
715 if(pPresentParms->EnableAutoDepthStencil) {
716 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
717 DepthStencilFormat = pPresentParms->AutoDepthStencilFormat;
720 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
721 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
722 if(!GL_SUPPORT(ARB_MULTISAMPLE))
723 ERR("The program is requesting multisampling without support!\n");
725 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
726 numSamples = pPresentParms->MultiSampleType;
730 /* Try to find a pixel format which matches our requirements */
731 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
733 /* Try to locate a compatible format if we weren't able to find anything */
735 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
736 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
739 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
741 ERR("Can't find a suitable iPixelFormat\n");
745 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
746 res = SetPixelFormat(hdc, iPixelFormat, NULL);
748 int oldPixelFormat = GetPixelFormat(hdc);
750 /* By default WGL doesn't allow pixel format adjustments but we need it here.
751 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
752 * set the pixel format multiple times. Only use it when it is really needed. */
754 if(oldPixelFormat == iPixelFormat) {
755 /* We don't have to do anything as the formats are the same :) */
756 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
757 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
760 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
763 } else if(oldPixelFormat) {
764 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
765 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
766 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
768 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
774 ctx = pwglCreateContext(hdc);
775 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
778 ERR("Failed to create a WGL context\n");
780 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
781 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
785 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
787 ERR("Failed to add the newly created context to the context list\n");
788 pwglDeleteContext(ctx);
790 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
791 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
795 ret->surface = (IWineD3DSurface *) target;
796 ret->isPBuffer = create_pbuffer;
797 ret->tid = GetCurrentThreadId();
798 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
799 /* Create the dirty constants array and initialize them to dirty */
800 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
801 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
802 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
803 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
804 memset(ret->vshader_const_dirty, 1,
805 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
806 memset(ret->pshader_const_dirty, 1,
807 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
810 TRACE("Successfully created new context %p\n", ret);
812 list_init(&ret->fbo_list);
814 /* Set up the context defaults */
815 oldCtx = pwglGetCurrentContext();
816 oldDrawable = pwglGetCurrentDC();
817 if(oldCtx && oldDrawable) {
818 /* See comment in ActivateContext context switching */
819 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
821 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
822 ERR("Cannot activate context to set up defaults\n");
828 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
830 TRACE("Setting up the screen\n");
831 /* Clear the screen */
832 glClearColor(1.0, 0.0, 0.0, 0.0);
833 checkGLcall("glClearColor");
836 glClearStencil(0xffff);
838 checkGLcall("glClear");
840 glColor3f(1.0, 1.0, 1.0);
841 checkGLcall("glColor3f");
843 glEnable(GL_LIGHTING);
844 checkGLcall("glEnable");
846 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
847 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
849 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
850 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
852 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
853 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
855 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
856 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
857 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
858 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
860 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
861 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
862 * and textures in DIB sections(due to the memory protection).
864 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
865 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
867 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
868 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
869 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
870 * GL_VERTEX_BLEND_ARB isn't enabled too
872 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
873 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
875 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
876 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
877 * the previous texture where to source the offset from is always unit - 1.
879 for(s = 1; s < GL_LIMITS(textures); s++) {
880 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
881 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
882 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
886 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
887 for(s = 0; s < GL_LIMITS(textures); s++) {
888 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
889 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
890 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
895 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
896 * but enable it for the first context we create, and reenable it on the old context
898 if(oldDrawable && oldCtx) {
899 pwglMakeCurrent(oldDrawable, oldCtx);
903 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
911 /*****************************************************************************
912 * RemoveContextFromArray
914 * Removes a context from the context manager. The opengl context is not
915 * destroyed or unset. context is not a valid pointer after that call.
917 * Similar to the former call this isn't a performance critical function. A
918 * helper function for DestroyContext.
921 * This: Device to activate the context for
922 * context: Context to remove
924 *****************************************************************************/
925 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
927 WineD3DContext **oldArray = This->contexts;
929 TRACE("Removing ctx %p\n", context);
933 if(This->numContexts) {
934 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
935 if(!This->contexts) {
936 ERR("Cannot allocate a new context array, PANIC!!!\n");
939 /* Note that we decreased numContexts a few lines up, so use '<=' instead of '<' */
940 for(s = 0; s <= This->numContexts; s++) {
941 if(oldArray[s] == context) continue;
942 This->contexts[t] = oldArray[s];
946 This->contexts = NULL;
949 HeapFree(GetProcessHeap(), 0, context);
950 HeapFree(GetProcessHeap(), 0, oldArray);
953 /*****************************************************************************
956 * Destroys a wineD3DContext
959 * This: Device to activate the context for
960 * context: Context to destroy
962 *****************************************************************************/
963 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
964 struct fbo_entry *entry, *entry2;
966 TRACE("Destroying ctx %p\n", context);
968 /* The correct GL context needs to be active to cleanup the GL resources below */
969 if(pwglGetCurrentContext() != context->glCtx){
970 pwglMakeCurrent(context->hdc, context->glCtx);
976 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
977 context_destroy_fbo_entry(This, entry);
979 if (context->src_fbo) {
980 TRACE("Destroy src FBO %d\n", context->src_fbo);
981 context_destroy_fbo(This, &context->src_fbo);
983 if (context->dst_fbo) {
984 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
985 context_destroy_fbo(This, &context->dst_fbo);
990 /* Cleanup the GL context */
991 pwglMakeCurrent(NULL, NULL);
992 if(context->isPBuffer) {
993 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
994 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
995 } else ReleaseDC(context->win_handle, context->hdc);
996 pwglDeleteContext(context->glCtx);
998 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
999 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1000 RemoveContextFromArray(This, context);
1003 static inline void set_blit_dimension(UINT width, UINT height) {
1004 glMatrixMode(GL_PROJECTION);
1005 checkGLcall("glMatrixMode(GL_PROJECTION)");
1007 checkGLcall("glLoadIdentity()");
1008 glOrtho(0, width, height, 0, 0.0, -1.0);
1009 checkGLcall("glOrtho");
1010 glViewport(0, 0, width, height);
1011 checkGLcall("glViewport");
1014 /*****************************************************************************
1017 * Sets up a context for DirectDraw blitting.
1018 * All texture units are disabled, texture unit 0 is set as current unit
1019 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1020 * color writing enabled for all channels
1021 * register combiners disabled, shaders disabled
1022 * world matrix is set to identity, texture matrix 0 too
1023 * projection matrix is setup for drawing screen coordinates
1026 * This: Device to activate the context for
1027 * context: Context to setup
1028 * width: render target width
1029 * height: render target height
1031 *****************************************************************************/
1032 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
1034 const struct StateEntry *StateTable = This->StateTable;
1036 TRACE("Setting up context %p for blitting\n", context);
1037 if(context->last_was_blit) {
1038 if(context->blit_w != width || context->blit_h != height) {
1039 set_blit_dimension(width, height);
1040 context->blit_w = width; context->blit_h = height;
1041 /* No need to dirtify here, the states are still dirtified because they weren't
1042 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1046 TRACE("Context is already set up for blitting, nothing to do\n");
1049 context->last_was_blit = TRUE;
1051 /* TODO: Use a display list */
1053 /* Disable shaders */
1054 This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
1055 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1056 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1058 /* Disable all textures. The caller can then bind a texture it wants to blit
1061 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
1062 /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1063 * function texture unit. No need to care for higher samplers
1065 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
1066 sampler = This->rev_tex_unit_map[i];
1067 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1068 checkGLcall("glActiveTextureARB");
1070 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1071 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1072 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1074 glDisable(GL_TEXTURE_3D);
1075 checkGLcall("glDisable GL_TEXTURE_3D");
1076 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1077 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1078 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1080 glDisable(GL_TEXTURE_2D);
1081 checkGLcall("glDisable GL_TEXTURE_2D");
1083 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1084 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1086 if (sampler != -1) {
1087 if (sampler < MAX_TEXTURES) {
1088 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1090 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1093 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1094 checkGLcall("glActiveTextureARB");
1097 sampler = This->rev_tex_unit_map[0];
1099 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1100 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1101 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1103 glDisable(GL_TEXTURE_3D);
1104 checkGLcall("glDisable GL_TEXTURE_3D");
1105 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1106 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1107 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1109 glDisable(GL_TEXTURE_2D);
1110 checkGLcall("glDisable GL_TEXTURE_2D");
1112 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1114 glMatrixMode(GL_TEXTURE);
1115 checkGLcall("glMatrixMode(GL_TEXTURE)");
1117 checkGLcall("glLoadIdentity()");
1119 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
1120 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1121 GL_TEXTURE_LOD_BIAS_EXT,
1123 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1126 if (sampler != -1) {
1127 if (sampler < MAX_TEXTURES) {
1128 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1129 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1131 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1134 /* Other misc states */
1135 glDisable(GL_ALPHA_TEST);
1136 checkGLcall("glDisable(GL_ALPHA_TEST)");
1137 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1138 glDisable(GL_LIGHTING);
1139 checkGLcall("glDisable GL_LIGHTING");
1140 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1141 glDisable(GL_DEPTH_TEST);
1142 checkGLcall("glDisable GL_DEPTH_TEST");
1143 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1145 checkGLcall("glDisable GL_FOG");
1146 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1147 glDisable(GL_BLEND);
1148 checkGLcall("glDisable GL_BLEND");
1149 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1150 glDisable(GL_CULL_FACE);
1151 checkGLcall("glDisable GL_CULL_FACE");
1152 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1153 glDisable(GL_STENCIL_TEST);
1154 checkGLcall("glDisable GL_STENCIL_TEST");
1155 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1156 glDisable(GL_SCISSOR_TEST);
1157 checkGLcall("glDisable GL_SCISSOR_TEST");
1158 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1159 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
1160 glDisable(GL_POINT_SPRITE_ARB);
1161 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1162 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1164 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1165 checkGLcall("glColorMask");
1166 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1167 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
1168 glDisable(GL_COLOR_SUM_EXT);
1169 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1170 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1173 /* Setup transforms */
1174 glMatrixMode(GL_MODELVIEW);
1175 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1177 checkGLcall("glLoadIdentity()");
1178 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1180 context->last_was_rhw = TRUE;
1181 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1183 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1184 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1185 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1186 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1187 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1188 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1189 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1191 set_blit_dimension(width, height);
1192 context->blit_w = width; context->blit_h = height;
1193 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1194 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1197 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1200 /*****************************************************************************
1201 * findThreadContextForSwapChain
1203 * Searches a swapchain for all contexts and picks one for the thread tid.
1204 * If none can be found the swapchain is requested to create a new context
1206 *****************************************************************************/
1207 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
1210 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1211 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1212 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1217 /* Create a new context for the thread */
1218 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
1221 /*****************************************************************************
1224 * Finds a context for the current render target and thread
1227 * target: Render target to find the context for
1228 * tid: Thread to activate the context for
1230 * Returns: The needed context
1232 *****************************************************************************/
1233 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
1234 IWineD3DSwapChain *swapchain = NULL;
1236 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
1237 WineD3DContext *context = This->activeContext;
1238 BOOL oldRenderOffscreen = This->render_offscreen;
1239 const WINED3DFORMAT oldFmt = ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->resource.format;
1240 const WINED3DFORMAT newFmt = ((IWineD3DSurfaceImpl *) target)->resource.format;
1241 const struct StateEntry *StateTable = This->StateTable;
1243 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1244 * the alpha blend state changes with different render target formats
1246 if(oldFmt != newFmt) {
1247 const GlPixelFormatDesc *glDesc;
1248 const StaticPixelFormatDesc *old = getFormatDescEntry(oldFmt, NULL, NULL);
1249 const StaticPixelFormatDesc *new = getFormatDescEntry(newFmt, &GLINFO_LOCATION, &glDesc);
1251 /* Disable blending when the alphaMask has changed and when a format doesn't support blending */
1252 if((old->alphaMask && !new->alphaMask) || (!old->alphaMask && new->alphaMask) || !(glDesc->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING)) {
1253 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1257 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
1258 if(hr == WINED3D_OK && swapchain) {
1259 TRACE("Rendering onscreen\n");
1261 context = findThreadContextForSwapChain(swapchain, tid);
1263 This->render_offscreen = FALSE;
1264 /* The context != This->activeContext will catch a NOP context change. This can occur
1265 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1266 * rendering. No context change is needed in that case
1269 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1270 if(This->pbufferContext && tid == This->pbufferContext->tid) {
1271 This->pbufferContext->tid = 0;
1274 IWineD3DSwapChain_Release(swapchain);
1276 if(oldRenderOffscreen) {
1277 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1278 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1279 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1280 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1281 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1285 TRACE("Rendering offscreen\n");
1286 This->render_offscreen = TRUE;
1288 switch(wined3d_settings.offscreen_rendering_mode) {
1290 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1291 if(This->activeContext && tid == This->lastThread) {
1292 context = This->activeContext;
1294 /* This may happen if the app jumps straight into offscreen rendering
1295 * Start using the context of the primary swapchain. tid == 0 is no problem
1296 * for findThreadContextForSwapChain.
1298 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1299 * is perfect to call.
1301 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1307 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
1308 if(This->pbufferContext == NULL ||
1309 This->pbufferWidth < targetimpl->currentDesc.Width ||
1310 This->pbufferHeight < targetimpl->currentDesc.Height) {
1311 if(This->pbufferContext) {
1312 DestroyContext(This, This->pbufferContext);
1315 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1316 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1318 This->pbufferContext = CreateContext(This, targetimpl,
1319 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1320 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1321 This->pbufferWidth = targetimpl->currentDesc.Width;
1322 This->pbufferHeight = targetimpl->currentDesc.Height;
1325 if(This->pbufferContext) {
1326 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1327 FIXME("The PBuffr context is only supported for one thread for now!\n");
1329 This->pbufferContext->tid = tid;
1330 context = This->pbufferContext;
1333 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1334 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1338 case ORM_BACKBUFFER:
1339 /* Stay with the currently active context for back buffer rendering */
1340 if(This->activeContext && tid == This->lastThread) {
1341 context = This->activeContext;
1343 /* This may happen if the app jumps straight into offscreen rendering
1344 * Start using the context of the primary swapchain. tid == 0 is no problem
1345 * for findThreadContextForSwapChain.
1347 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1348 * is perfect to call.
1350 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1355 if(!oldRenderOffscreen) {
1356 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1357 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1358 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1359 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1360 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1364 /* When switching away from an offscreen render target, and we're not using FBOs,
1365 * we have to read the drawable into the texture. This is done via PreLoad(and
1366 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1367 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1368 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1369 * is read. This leads to these possible situations:
1371 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1372 * Nothing to do, we don't even reach this code in this case...
1374 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1375 * The currently active context is OK for readback. Call PreLoad, and it
1378 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1379 * Nothing to do - the drawable is unchanged
1381 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1382 * This is tricky. We have to get a context with the old drawable from somewhere
1383 * before we can switch to the new context. In this case, PreLoad calls
1384 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1385 * is case (2) then. The old drawable is activated for the new thread, and the
1386 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1387 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1388 * target for the new thread
1390 if (readTexture && This->lastActiveRenderTarget != target) {
1391 BOOL oldInDraw = This->isInDraw;
1393 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1394 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1395 * when using offscreen rendering with multithreading
1397 This->isInDraw = TRUE;
1399 /* Do that before switching the context:
1400 * Read the back buffer of the old drawable into the destination texture
1402 IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
1404 /* Assume that the drawable will be modified by some other things now */
1405 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1407 This->isInDraw = oldInDraw;
1413 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1416 IWineD3DSwapChain *swapchain;
1418 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain);
1421 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1422 glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1423 checkGLcall("glDrawBuffers()");
1427 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1431 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1433 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1434 checkGLcall("glDrawBuffers()");
1438 glDrawBuffer(This->draw_buffers[0]);
1439 checkGLcall("glDrawBuffer()");
1442 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1443 checkGLcall("glDrawBuffer()");
1448 glDrawBuffer(This->offscreenBuffer);
1449 checkGLcall("glDrawBuffer()");
1454 /*****************************************************************************
1457 * Finds a rendering context and drawable matching the device and render
1458 * target for the current thread, activates them and puts them into the
1462 * This: Device to activate the context for
1463 * target: Requested render target
1464 * usage: Prepares the context for blitting, drawing or other actions
1466 *****************************************************************************/
1467 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1468 DWORD tid = GetCurrentThreadId();
1470 DWORD dirtyState, idx;
1472 WineD3DContext *context;
1473 const struct StateEntry *StateTable = This->StateTable;
1475 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1476 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1477 context = FindContext(This, target, tid);
1478 context->draw_buffer_dirty = TRUE;
1479 This->lastActiveRenderTarget = target;
1480 This->lastThread = tid;
1482 /* Stick to the old context */
1483 context = This->activeContext;
1486 /* Activate the opengl context */
1487 if(last_device != This || context != This->activeContext) {
1490 /* Prevent an unneeded context switch as those are expensive */
1491 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1492 TRACE("Already using gl context %p\n", context->glCtx);
1495 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1497 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1498 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1500 ERR("Failed to activate the new context\n");
1501 } else if(!context->last_was_blit) {
1502 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1505 if(This->activeContext->vshader_const_dirty) {
1506 memset(This->activeContext->vshader_const_dirty, 1,
1507 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1509 if(This->activeContext->pshader_const_dirty) {
1510 memset(This->activeContext->pshader_const_dirty, 1,
1511 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1513 This->activeContext = context;
1517 /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
1521 case CTXUSAGE_CLEAR:
1522 case CTXUSAGE_DRAWPRIM:
1523 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1524 context_apply_fbo_state((IWineD3DDevice *)This);
1526 if (context->draw_buffer_dirty) {
1527 apply_draw_buffer(This, target, FALSE);
1528 context->draw_buffer_dirty = FALSE;
1533 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1534 if (This->render_offscreen) {
1535 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1536 context_bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1537 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1538 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0));
1539 checkGLcall("glFramebufferRenderbufferEXT");
1541 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1542 checkGLcall("glFramebufferRenderbufferEXT");
1544 context->draw_buffer_dirty = TRUE;
1546 if (context->draw_buffer_dirty) {
1547 apply_draw_buffer(This, target, TRUE);
1548 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1549 context->draw_buffer_dirty = FALSE;
1559 case CTXUSAGE_RESOURCELOAD:
1560 /* This does not require any special states to be set up */
1563 case CTXUSAGE_CLEAR:
1564 if(context->last_was_blit) {
1565 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1568 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1569 * blending when clearing improves the clearing performance incredibly.
1571 glDisable(GL_BLEND);
1572 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1574 glEnable(GL_SCISSOR_TEST);
1575 checkGLcall("glEnable GL_SCISSOR_TEST");
1576 context->last_was_blit = FALSE;
1577 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1578 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1581 case CTXUSAGE_DRAWPRIM:
1582 /* This needs all dirty states applied */
1583 if(context->last_was_blit) {
1584 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1587 IWineD3DDeviceImpl_FindTexUnitMap(This);
1589 for(i=0; i < context->numDirtyEntries; i++) {
1590 dirtyState = context->dirtyArray[i];
1591 idx = dirtyState >> 5;
1592 shift = dirtyState & 0x1f;
1593 context->isStateDirty[idx] &= ~(1 << shift);
1594 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1596 context->numDirtyEntries = 0; /* This makes the whole list clean */
1597 context->last_was_blit = FALSE;
1601 SetupForBlit(This, context,
1602 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1603 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1607 FIXME("Unexpected context usage requested\n");