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, update_magfilter;
82 /* Update base texture states array */
83 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
85 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT)
87 texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
88 update_minfilter = TRUE;
91 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
93 texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
94 update_magfilter = TRUE;
97 if (texture_impl->baseTexture.bindCount)
99 WARN("Render targets should not be bound to a sampler\n");
100 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(texture_impl->baseTexture.sampler));
103 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
106 if (update_minfilter || update_magfilter || force_preload)
108 GLenum target, bind_target;
111 target = surface_impl->glDescription.target;
112 if (target == GL_TEXTURE_2D)
114 bind_target = GL_TEXTURE_2D;
115 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
116 } else if (target == GL_TEXTURE_RECTANGLE_ARB) {
117 bind_target = GL_TEXTURE_RECTANGLE_ARB;
118 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
120 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
121 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
124 IWineD3DSurface_PreLoad(surface);
126 glBindTexture(bind_target, surface_impl->glDescription.textureName);
127 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
128 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
129 glBindTexture(bind_target, old_binding);
132 checkGLcall("apply_attachment_filter_states()");
135 /* TODO: Handle stencil attachments */
136 void context_attach_depth_stencil_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
138 IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
140 if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
142 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
143 checkGLcall("glFramebufferRenderbufferEXT()");
145 context_apply_attachment_filter_states((IWineD3DDevice *)This, depth_stencil, TRUE);
147 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, depth_stencil_impl->glDescription.target,
148 depth_stencil_impl->glDescription.textureName, depth_stencil_impl->glDescription.level));
149 checkGLcall("glFramebufferTexture2DEXT()");
153 void context_attach_surface_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
155 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
157 context_apply_attachment_filter_states((IWineD3DDevice *)This, surface, TRUE);
159 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, surface_impl->glDescription.target,
160 surface_impl->glDescription.textureName, surface_impl->glDescription.level));
162 checkGLcall("attach_surface_fbo");
165 /* TODO: Handle stencil attachments */
166 static void context_set_depth_stencil_fbo(IWineD3DDevice *iface, IWineD3DSurface *depth_stencil)
168 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
170 TRACE("Set depth stencil to %p\n", depth_stencil);
174 context_attach_depth_stencil_fbo(This, GL_FRAMEBUFFER_EXT, depth_stencil, TRUE);
176 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
177 checkGLcall("glFramebufferTexture2DEXT()");
181 static void context_set_render_target_fbo(IWineD3DDevice *iface, DWORD idx, IWineD3DSurface *render_target)
183 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
185 TRACE("Set render target %u to %p\n", idx, render_target);
189 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, idx, render_target);
191 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + idx, GL_TEXTURE_2D, 0, 0));
192 checkGLcall("glFramebufferTexture2DEXT()");
196 static void context_check_fbo_status(IWineD3DDevice *iface)
198 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
201 status = GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
202 if (status == GL_FRAMEBUFFER_COMPLETE_EXT)
204 TRACE("FBO complete\n");
206 IWineD3DSurfaceImpl *attachment;
208 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
210 /* Dump the FBO attachments */
211 for (i = 0; i < GL_LIMITS(buffers); ++i)
213 attachment = (IWineD3DSurfaceImpl *)This->activeContext->fbo_color_attachments[i];
216 FIXME("\tColor attachment %d: (%p) %s %ux%u\n", i, attachment, debug_d3dformat(attachment->resource.format),
217 attachment->pow2Width, attachment->pow2Height);
220 attachment = (IWineD3DSurfaceImpl *)This->activeContext->fbo_depth_attachment;
223 FIXME("\tDepth attachment: (%p) %s %ux%u\n", attachment, debug_d3dformat(attachment->resource.format),
224 attachment->pow2Width, attachment->pow2Height);
229 static BOOL context_depth_mismatch_fbo(IWineD3DDevice *iface)
231 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
232 IWineD3DSurfaceImpl *rt_impl = (IWineD3DSurfaceImpl *)This->render_targets[0];
233 IWineD3DSurfaceImpl *ds_impl = (IWineD3DSurfaceImpl *)This->stencilBufferTarget;
235 if (!ds_impl) return FALSE;
237 if (ds_impl->current_renderbuffer)
239 return (rt_impl->pow2Width != ds_impl->current_renderbuffer->width ||
240 rt_impl->pow2Height != ds_impl->current_renderbuffer->height);
243 return (rt_impl->pow2Width != ds_impl->pow2Width ||
244 rt_impl->pow2Height != ds_impl->pow2Height);
247 void context_apply_fbo_state(IWineD3DDevice *iface)
249 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
250 WineD3DContext *context = This->activeContext;
253 if (This->render_offscreen)
255 context_bind_fbo(iface, GL_FRAMEBUFFER_EXT, &context->fbo);
257 /* Apply render targets */
258 for (i = 0; i < GL_LIMITS(buffers); ++i)
260 IWineD3DSurface *render_target = This->render_targets[i];
261 if (context->fbo_color_attachments[i] != render_target)
263 context_set_render_target_fbo(iface, i, render_target);
264 context->fbo_color_attachments[i] = render_target;
268 /* Apply depth targets */
269 if (context->fbo_depth_attachment != This->stencilBufferTarget || context_depth_mismatch_fbo(iface))
271 unsigned int w = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Width;
272 unsigned int h = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Height;
274 if (This->stencilBufferTarget)
276 surface_set_compatible_renderbuffer(This->stencilBufferTarget, w, h);
278 context_set_depth_stencil_fbo(iface, This->stencilBufferTarget);
279 context->fbo_depth_attachment = This->stencilBufferTarget;
282 for (i = 0; i < GL_LIMITS(buffers); ++i)
284 if (This->render_targets[i])
285 This->draw_buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
287 This->draw_buffers[i] = GL_NONE;
290 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
293 context_check_fbo_status(iface);
296 /*****************************************************************************
297 * Context_MarkStateDirty
299 * Marks a state in a context dirty. Only one context, opposed to
300 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
304 * context: Context to mark the state dirty in
305 * state: State to mark dirty
306 * StateTable: Pointer to the state table in use(for state grouping)
308 *****************************************************************************/
309 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
310 DWORD rep = StateTable[state].representative;
314 if(!rep || isStateDirty(context, rep)) return;
316 context->dirtyArray[context->numDirtyEntries++] = rep;
319 context->isStateDirty[idx] |= (1 << shift);
322 /*****************************************************************************
325 * Adds a context to the context array. Helper function for CreateContext
327 * This method is not called in performance-critical code paths, only when a
328 * new render target or swapchain is created. Thus performance is not an issue
332 * This: Device to add the context for
333 * hdc: device context
334 * glCtx: WGL context to add
335 * pbuffer: optional pbuffer used with this context
337 *****************************************************************************/
338 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
339 WineD3DContext **oldArray = This->contexts;
342 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
343 if(This->contexts == NULL) {
344 ERR("Unable to grow the context array\n");
345 This->contexts = oldArray;
349 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
352 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
353 if(This->contexts[This->numContexts] == NULL) {
354 ERR("Unable to allocate a new context\n");
355 HeapFree(GetProcessHeap(), 0, This->contexts);
356 This->contexts = oldArray;
360 This->contexts[This->numContexts]->hdc = hdc;
361 This->contexts[This->numContexts]->glCtx = glCtx;
362 This->contexts[This->numContexts]->pbuffer = pbuffer;
363 This->contexts[This->numContexts]->win_handle = win_handle;
364 HeapFree(GetProcessHeap(), 0, oldArray);
366 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
368 for(state = 0; state <= STATE_HIGHEST; state++) {
369 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
373 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
374 return This->contexts[This->numContexts - 1];
377 /* This function takes care of WineD3D pixel format selection. */
378 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc, WINED3DFORMAT ColorFormat, WINED3DFORMAT DepthStencilFormat, BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
380 int iPixelFormat=0, matchtry;
381 short redBits, greenBits, blueBits, alphaBits, colorBits;
382 short depthBits=0, stencilBits=0;
389 /* First, try without alpha match buffers. MacOS supports aux buffers only
390 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
391 * Then try without aux buffers - this is the most common cause for not
392 * finding a pixel format. Also some drivers(the open source ones)
393 * only offer 32 bit ARB pixel formats. First try without an exact alpha
394 * match, then try without an exact alpha and color match.
396 { TRUE, TRUE, TRUE },
397 { TRUE, FALSE, TRUE },
398 { FALSE, TRUE, TRUE },
399 { FALSE, FALSE, TRUE },
400 { TRUE, FALSE, FALSE },
401 { FALSE, FALSE, FALSE },
405 int nCfgs = This->adapter->nCfgs;
406 WineD3D_PixelFormat *cfgs = This->adapter->cfgs;
408 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
409 debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat), auxBuffers, numSamples, pbuffer, findCompatible);
411 if(!getColorBits(ColorFormat, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
412 ERR("Unable to get color bits for format %s (%#x)!\n", debug_d3dformat(ColorFormat), ColorFormat);
416 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
417 * You are able to add a depth + stencil surface at a later stage when you need it.
418 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
419 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
420 * context, need torecreate shaders, textures and other resources.
422 * The context manager already takes care of the state problem and for the other tasks code from Reset
423 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
424 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
425 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
426 * issue needs to be fixed. */
427 if(DepthStencilFormat != WINED3DFMT_D24S8)
428 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
430 DepthStencilFormat = WINED3DFMT_D24S8;
432 if(DepthStencilFormat) {
433 getDepthStencilBits(DepthStencilFormat, &depthBits, &stencilBits);
436 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
437 for(i=0; i<nCfgs; i++) {
438 BOOL exactDepthMatch = TRUE;
439 cfgs = &This->adapter->cfgs[i];
441 /* For now only accept RGBA formats. Perhaps some day we will
442 * allow floating point formats for pbuffers. */
443 if(cfgs->iPixelType != WGL_TYPE_RGBA_ARB)
446 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
447 if(!pbuffer && !(cfgs->windowDrawable && cfgs->doubleBuffer))
450 /* We like to have aux buffers in backbuffer mode */
451 if(auxBuffers && !cfgs->auxBuffers && matches[matchtry].require_aux)
454 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
455 if(pbuffer && (!cfgs->pbufferDrawable || cfgs->doubleBuffer))
458 if(matches[matchtry].exact_color) {
459 if(cfgs->redSize != redBits)
461 if(cfgs->greenSize != greenBits)
463 if(cfgs->blueSize != blueBits)
466 if(cfgs->redSize < redBits)
468 if(cfgs->greenSize < greenBits)
470 if(cfgs->blueSize < blueBits)
473 if(matches[matchtry].exact_alpha) {
474 if(cfgs->alphaSize != alphaBits)
477 if(cfgs->alphaSize < alphaBits)
481 /* We try to locate a format which matches our requirements exactly. In case of
482 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
483 if(cfgs->depthSize < depthBits)
485 else if(cfgs->depthSize > depthBits)
486 exactDepthMatch = FALSE;
488 /* In all cases make sure the number of stencil bits matches our requirements
489 * even when we don't need stencil because it could affect performance EXCEPT
490 * on cards which don't offer depth formats without stencil like the i915 drivers
492 if(stencilBits != cfgs->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfgs->stencilSize))
495 /* Check multisampling support */
496 if(cfgs->numSamples != numSamples)
499 /* When we have passed all the checks then we have found a format which matches our
500 * requirements. Note that we only check for a limit number of capabilities right now,
501 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
502 * can still differ in things like multisampling, stereo, SRGB and other flags.
505 /* Exit the loop as we have found a format :) */
506 if(exactDepthMatch) {
507 iPixelFormat = cfgs->iPixelFormat;
509 } else if(!iPixelFormat) {
510 /* In the end we might end up with a format which doesn't exactly match our depth
511 * requirements. Accept the first format we found because formats with higher iPixelFormat
512 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
513 iPixelFormat = cfgs->iPixelFormat;
518 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
519 if(!iPixelFormat && !findCompatible) {
520 ERR("Can't find a suitable iPixelFormat\n");
522 } else if(!iPixelFormat) {
523 PIXELFORMATDESCRIPTOR pfd;
525 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
526 /* PixelFormat selection */
527 ZeroMemory(&pfd, sizeof(pfd));
528 pfd.nSize = sizeof(pfd);
530 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
531 pfd.iPixelType = PFD_TYPE_RGBA;
532 pfd.cAlphaBits = alphaBits;
533 pfd.cColorBits = colorBits;
534 pfd.cDepthBits = depthBits;
535 pfd.cStencilBits = stencilBits;
536 pfd.iLayerType = PFD_MAIN_PLANE;
538 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
540 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
541 ERR("Can't find a suitable iPixelFormat\n");
546 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n", iPixelFormat, debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat));
550 /*****************************************************************************
553 * Creates a new context for a window, or a pbuffer context.
556 * This: Device to activate the context for
557 * target: Surface this context will render to
558 * win_handle: handle to the window which we are drawing to
559 * create_pbuffer: tells whether to create a pbuffer or not
560 * pPresentParameters: contains the pixelformats to use for onscreen rendering
562 *****************************************************************************/
563 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
564 HDC oldDrawable, hdc;
565 HPBUFFERARB pbuffer = NULL;
566 HGLRC ctx = NULL, oldCtx;
567 WineD3DContext *ret = NULL;
570 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
573 HDC hdc_parent = GetDC(win_handle);
574 int iPixelFormat = 0;
576 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
577 WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
579 /* Try to find a pixel format with pbuffer support. */
580 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */, FALSE /* findCompatible */);
582 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
584 /* For some reason we weren't able to find a format, try to find something instead of crashing.
585 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
586 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */, TRUE /* findCompatible */);
589 /* This shouldn't happen as ChoosePixelFormat always returns something */
591 ERR("Unable to locate a pixel format for a pbuffer\n");
592 ReleaseDC(win_handle, hdc_parent);
596 TRACE("Creating a pBuffer drawable for the new context\n");
597 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
599 ERR("Cannot create a pbuffer\n");
600 ReleaseDC(win_handle, hdc_parent);
604 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
605 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
607 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
608 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
609 ReleaseDC(win_handle, hdc_parent);
612 ReleaseDC(win_handle, hdc_parent);
614 PIXELFORMATDESCRIPTOR pfd;
617 WINED3DFORMAT ColorFormat = target->resource.format;
618 WINED3DFORMAT DepthStencilFormat = 0;
619 BOOL auxBuffers = FALSE;
622 hdc = GetDC(win_handle);
624 ERR("Cannot retrieve a device context!\n");
628 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
629 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
632 if(target->resource.format == WINED3DFMT_X4R4G4B4)
633 ColorFormat = WINED3DFMT_A4R4G4B4;
634 else if(target->resource.format == WINED3DFMT_X8R8G8B8)
635 ColorFormat = WINED3DFMT_A8R8G8B8;
638 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
639 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
640 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
641 * a format with 8bit alpha, so request A8R8G8B8. */
642 if(ColorFormat == WINED3DFMT_P8)
643 ColorFormat = WINED3DFMT_A8R8G8B8;
645 /* Retrieve the depth stencil format from the present parameters.
646 * The choice of the proper format can give a nice performance boost
647 * in case of GPU limited programs. */
648 if(pPresentParms->EnableAutoDepthStencil) {
649 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
650 DepthStencilFormat = pPresentParms->AutoDepthStencilFormat;
653 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
654 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
655 if(!GL_SUPPORT(ARB_MULTISAMPLE))
656 ERR("The program is requesting multisampling without support!\n");
658 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
659 numSamples = pPresentParms->MultiSampleType;
663 /* Try to find a pixel format which matches our requirements */
664 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
666 /* Try to locate a compatible format if we weren't able to find anything */
668 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
669 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
672 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
674 ERR("Can't find a suitable iPixelFormat\n");
678 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
679 res = SetPixelFormat(hdc, iPixelFormat, NULL);
681 int oldPixelFormat = GetPixelFormat(hdc);
683 /* By default WGL doesn't allow pixel format adjustments but we need it here.
684 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
685 * set the pixel format multiple times. Only use it when it is really needed. */
687 if(oldPixelFormat == iPixelFormat) {
688 /* We don't have to do anything as the formats are the same :) */
689 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
690 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
693 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
696 } else if(oldPixelFormat) {
697 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
698 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
699 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
701 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
707 ctx = pwglCreateContext(hdc);
708 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
711 ERR("Failed to create a WGL context\n");
713 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
714 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
718 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
720 ERR("Failed to add the newly created context to the context list\n");
721 pwglDeleteContext(ctx);
723 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
724 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
728 ret->surface = (IWineD3DSurface *) target;
729 ret->isPBuffer = create_pbuffer;
730 ret->tid = GetCurrentThreadId();
731 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
732 /* Create the dirty constants array and initialize them to dirty */
733 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
734 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
735 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
736 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
737 memset(ret->vshader_const_dirty, 1,
738 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
739 memset(ret->pshader_const_dirty, 1,
740 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
743 TRACE("Successfully created new context %p\n", ret);
745 ret->fbo_color_attachments = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IWineD3DSurface *) * GL_LIMITS(buffers));
746 if (!ret->fbo_color_attachments)
748 ERR("Out of memory!\n");
752 /* Set up the context defaults */
753 oldCtx = pwglGetCurrentContext();
754 oldDrawable = pwglGetCurrentDC();
755 if(oldCtx && oldDrawable) {
756 /* See comment in ActivateContext context switching */
757 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
759 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
760 ERR("Cannot activate context to set up defaults\n");
766 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
768 TRACE("Setting up the screen\n");
769 /* Clear the screen */
770 glClearColor(1.0, 0.0, 0.0, 0.0);
771 checkGLcall("glClearColor");
774 glClearStencil(0xffff);
776 checkGLcall("glClear");
778 glColor3f(1.0, 1.0, 1.0);
779 checkGLcall("glColor3f");
781 glEnable(GL_LIGHTING);
782 checkGLcall("glEnable");
784 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
785 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
787 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
788 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
790 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
791 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
793 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
794 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
795 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
796 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
798 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
799 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
800 * and textures in DIB sections(due to the memory protection).
802 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
803 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
805 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
806 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
807 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
808 * GL_VERTEX_BLEND_ARB isn't enabled too
810 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
811 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
813 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
814 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
815 * the previous texture where to source the offset from is always unit - 1.
817 for(s = 1; s < GL_LIMITS(textures); s++) {
818 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
819 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
820 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
824 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
825 for(s = 0; s < GL_LIMITS(textures); s++) {
826 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
827 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
828 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
833 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
834 * but enable it for the first context we create, and reenable it on the old context
836 if(oldDrawable && oldCtx) {
837 pwglMakeCurrent(oldDrawable, oldCtx);
841 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
846 HeapFree(GetProcessHeap(), 0, ret->fbo_color_attachments);
850 /*****************************************************************************
851 * RemoveContextFromArray
853 * Removes a context from the context manager. The opengl context is not
854 * destroyed or unset. context is not a valid pointer after that call.
856 * Similar to the former call this isn't a performance critical function. A
857 * helper function for DestroyContext.
860 * This: Device to activate the context for
861 * context: Context to remove
863 *****************************************************************************/
864 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
866 WineD3DContext **oldArray = This->contexts;
868 TRACE("Removing ctx %p\n", context);
872 if(This->numContexts) {
873 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
874 if(!This->contexts) {
875 ERR("Cannot allocate a new context array, PANIC!!!\n");
878 /* Note that we decreased numContexts a few lines up, so use '<=' instead of '<' */
879 for(s = 0; s <= This->numContexts; s++) {
880 if(oldArray[s] == context) continue;
881 This->contexts[t] = oldArray[s];
885 This->contexts = NULL;
888 HeapFree(GetProcessHeap(), 0, context);
889 HeapFree(GetProcessHeap(), 0, oldArray);
892 /*****************************************************************************
895 * Destroys a wineD3DContext
898 * This: Device to activate the context for
899 * context: Context to destroy
901 *****************************************************************************/
902 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
904 TRACE("Destroying ctx %p\n", context);
906 /* The correct GL context needs to be active to cleanup the GL resources below */
907 if(pwglGetCurrentContext() != context->glCtx){
908 pwglMakeCurrent(context->hdc, context->glCtx);
915 TRACE("Destroy FBO %d\n", context->fbo);
916 context_destroy_fbo(This, &context->fbo);
918 if (context->src_fbo) {
919 TRACE("Destroy src FBO %d\n", context->src_fbo);
920 context_destroy_fbo(This, &context->src_fbo);
922 if (context->dst_fbo) {
923 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
924 context_destroy_fbo(This, &context->dst_fbo);
929 HeapFree(GetProcessHeap(), 0, context->fbo_color_attachments);
930 context->fbo_color_attachments = NULL;
932 /* Cleanup the GL context */
933 pwglMakeCurrent(NULL, NULL);
934 if(context->isPBuffer) {
935 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
936 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
937 } else ReleaseDC(context->win_handle, context->hdc);
938 pwglDeleteContext(context->glCtx);
940 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
941 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
942 RemoveContextFromArray(This, context);
945 static inline void set_blit_dimension(UINT width, UINT height) {
946 glMatrixMode(GL_PROJECTION);
947 checkGLcall("glMatrixMode(GL_PROJECTION)");
949 checkGLcall("glLoadIdentity()");
950 glOrtho(0, width, height, 0, 0.0, -1.0);
951 checkGLcall("glOrtho");
952 glViewport(0, 0, width, height);
953 checkGLcall("glViewport");
956 /*****************************************************************************
959 * Sets up a context for DirectDraw blitting.
960 * All texture units are disabled, texture unit 0 is set as current unit
961 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
962 * color writing enabled for all channels
963 * register combiners disabled, shaders disabled
964 * world matrix is set to identity, texture matrix 0 too
965 * projection matrix is setup for drawing screen coordinates
968 * This: Device to activate the context for
969 * context: Context to setup
970 * width: render target width
971 * height: render target height
973 *****************************************************************************/
974 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
976 const struct StateEntry *StateTable = This->StateTable;
978 TRACE("Setting up context %p for blitting\n", context);
979 if(context->last_was_blit) {
980 if(context->blit_w != width || context->blit_h != height) {
981 set_blit_dimension(width, height);
982 context->blit_w = width; context->blit_h = height;
983 /* No need to dirtify here, the states are still dirtified because they weren't
984 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
988 TRACE("Context is already set up for blitting, nothing to do\n");
991 context->last_was_blit = TRUE;
993 /* TODO: Use a display list */
995 /* Disable shaders */
996 This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
997 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
998 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1000 /* Disable all textures. The caller can then bind a texture it wants to blit
1003 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
1004 /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1005 * function texture unit. No need to care for higher samplers
1007 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
1008 sampler = This->rev_tex_unit_map[i];
1009 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1010 checkGLcall("glActiveTextureARB");
1012 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1013 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1014 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1016 glDisable(GL_TEXTURE_3D);
1017 checkGLcall("glDisable GL_TEXTURE_3D");
1018 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1019 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1020 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1022 glDisable(GL_TEXTURE_2D);
1023 checkGLcall("glDisable GL_TEXTURE_2D");
1025 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1026 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1028 if (sampler != -1) {
1029 if (sampler < MAX_TEXTURES) {
1030 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1032 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1035 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1036 checkGLcall("glActiveTextureARB");
1039 sampler = This->rev_tex_unit_map[0];
1041 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1042 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1043 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1045 glDisable(GL_TEXTURE_3D);
1046 checkGLcall("glDisable GL_TEXTURE_3D");
1047 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1048 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1049 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1051 glDisable(GL_TEXTURE_2D);
1052 checkGLcall("glDisable GL_TEXTURE_2D");
1054 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1056 glMatrixMode(GL_TEXTURE);
1057 checkGLcall("glMatrixMode(GL_TEXTURE)");
1059 checkGLcall("glLoadIdentity()");
1061 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
1062 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1063 GL_TEXTURE_LOD_BIAS_EXT,
1065 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1068 if (sampler != -1) {
1069 if (sampler < MAX_TEXTURES) {
1070 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1071 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1073 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1076 /* Other misc states */
1077 glDisable(GL_ALPHA_TEST);
1078 checkGLcall("glDisable(GL_ALPHA_TEST)");
1079 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1080 glDisable(GL_LIGHTING);
1081 checkGLcall("glDisable GL_LIGHTING");
1082 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1083 glDisable(GL_DEPTH_TEST);
1084 checkGLcall("glDisable GL_DEPTH_TEST");
1085 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1087 checkGLcall("glDisable GL_FOG");
1088 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1089 glDisable(GL_BLEND);
1090 checkGLcall("glDisable GL_BLEND");
1091 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1092 glDisable(GL_CULL_FACE);
1093 checkGLcall("glDisable GL_CULL_FACE");
1094 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1095 glDisable(GL_STENCIL_TEST);
1096 checkGLcall("glDisable GL_STENCIL_TEST");
1097 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1098 glDisable(GL_SCISSOR_TEST);
1099 checkGLcall("glDisable GL_SCISSOR_TEST");
1100 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1101 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
1102 glDisable(GL_POINT_SPRITE_ARB);
1103 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1104 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1106 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1107 checkGLcall("glColorMask");
1108 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1109 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
1110 glDisable(GL_COLOR_SUM_EXT);
1111 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1112 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1115 /* Setup transforms */
1116 glMatrixMode(GL_MODELVIEW);
1117 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1119 checkGLcall("glLoadIdentity()");
1120 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1122 context->last_was_rhw = TRUE;
1123 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1125 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1126 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1127 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1128 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1129 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1130 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1131 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1133 set_blit_dimension(width, height);
1134 context->blit_w = width; context->blit_h = height;
1135 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1136 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1139 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1142 /*****************************************************************************
1143 * findThreadContextForSwapChain
1145 * Searches a swapchain for all contexts and picks one for the thread tid.
1146 * If none can be found the swapchain is requested to create a new context
1148 *****************************************************************************/
1149 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
1152 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1153 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1154 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1159 /* Create a new context for the thread */
1160 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
1163 /*****************************************************************************
1166 * Finds a context for the current render target and thread
1169 * target: Render target to find the context for
1170 * tid: Thread to activate the context for
1172 * Returns: The needed context
1174 *****************************************************************************/
1175 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
1176 IWineD3DSwapChain *swapchain = NULL;
1178 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
1179 WineD3DContext *context = This->activeContext;
1180 BOOL oldRenderOffscreen = This->render_offscreen;
1181 const WINED3DFORMAT oldFmt = ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->resource.format;
1182 const WINED3DFORMAT newFmt = ((IWineD3DSurfaceImpl *) target)->resource.format;
1183 const struct StateEntry *StateTable = This->StateTable;
1185 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1186 * the alpha blend state changes with different render target formats
1188 if(oldFmt != newFmt) {
1189 const GlPixelFormatDesc *glDesc;
1190 const StaticPixelFormatDesc *old = getFormatDescEntry(oldFmt, NULL, NULL);
1191 const StaticPixelFormatDesc *new = getFormatDescEntry(newFmt, &GLINFO_LOCATION, &glDesc);
1193 /* Disable blending when the alphaMask has changed and when a format doesn't support blending */
1194 if((old->alphaMask && !new->alphaMask) || (!old->alphaMask && new->alphaMask) || !(glDesc->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING)) {
1195 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1199 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
1200 if(hr == WINED3D_OK && swapchain) {
1201 TRACE("Rendering onscreen\n");
1203 context = findThreadContextForSwapChain(swapchain, tid);
1205 This->render_offscreen = FALSE;
1206 /* The context != This->activeContext will catch a NOP context change. This can occur
1207 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1208 * rendering. No context change is needed in that case
1211 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1212 if(This->pbufferContext && tid == This->pbufferContext->tid) {
1213 This->pbufferContext->tid = 0;
1216 IWineD3DSwapChain_Release(swapchain);
1218 if(oldRenderOffscreen) {
1219 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1220 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1221 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1222 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1223 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1227 TRACE("Rendering offscreen\n");
1228 This->render_offscreen = TRUE;
1230 switch(wined3d_settings.offscreen_rendering_mode) {
1232 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1233 if(This->activeContext && tid == This->lastThread) {
1234 context = This->activeContext;
1236 /* This may happen if the app jumps straight into offscreen rendering
1237 * Start using the context of the primary swapchain. tid == 0 is no problem
1238 * for findThreadContextForSwapChain.
1240 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1241 * is perfect to call.
1243 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1249 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
1250 if(This->pbufferContext == NULL ||
1251 This->pbufferWidth < targetimpl->currentDesc.Width ||
1252 This->pbufferHeight < targetimpl->currentDesc.Height) {
1253 if(This->pbufferContext) {
1254 DestroyContext(This, This->pbufferContext);
1257 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1258 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1260 This->pbufferContext = CreateContext(This, targetimpl,
1261 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1262 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1263 This->pbufferWidth = targetimpl->currentDesc.Width;
1264 This->pbufferHeight = targetimpl->currentDesc.Height;
1267 if(This->pbufferContext) {
1268 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1269 FIXME("The PBuffr context is only supported for one thread for now!\n");
1271 This->pbufferContext->tid = tid;
1272 context = This->pbufferContext;
1275 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1276 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1280 case ORM_BACKBUFFER:
1281 /* Stay with the currently active context for back buffer rendering */
1282 if(This->activeContext && tid == This->lastThread) {
1283 context = This->activeContext;
1285 /* This may happen if the app jumps straight into offscreen rendering
1286 * Start using the context of the primary swapchain. tid == 0 is no problem
1287 * for findThreadContextForSwapChain.
1289 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1290 * is perfect to call.
1292 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1297 if(!oldRenderOffscreen) {
1298 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1299 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1300 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1301 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1302 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1306 /* When switching away from an offscreen render target, and we're not using FBOs,
1307 * we have to read the drawable into the texture. This is done via PreLoad(and
1308 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1309 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1310 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1311 * is read. This leads to these possible situations:
1313 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1314 * Nothing to do, we don't even reach this code in this case...
1316 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1317 * The currently active context is OK for readback. Call PreLoad, and it
1320 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1321 * Nothing to do - the drawable is unchanged
1323 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1324 * This is tricky. We have to get a context with the old drawable from somewhere
1325 * before we can switch to the new context. In this case, PreLoad calls
1326 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1327 * is case (2) then. The old drawable is activated for the new thread, and the
1328 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1329 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1330 * target for the new thread
1332 if (readTexture && This->lastActiveRenderTarget != target) {
1333 BOOL oldInDraw = This->isInDraw;
1335 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1336 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1337 * when using offscreen rendering with multithreading
1339 This->isInDraw = TRUE;
1341 /* Do that before switching the context:
1342 * Read the back buffer of the old drawable into the destination texture
1344 IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
1346 /* Assume that the drawable will be modified by some other things now */
1347 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1349 This->isInDraw = oldInDraw;
1355 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1358 IWineD3DSwapChain *swapchain;
1360 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain);
1363 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1364 glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1365 checkGLcall("glDrawBuffers()");
1369 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1373 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1375 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1376 checkGLcall("glDrawBuffers()");
1380 glDrawBuffer(This->draw_buffers[0]);
1381 checkGLcall("glDrawBuffer()");
1384 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1385 checkGLcall("glDrawBuffer()");
1390 glDrawBuffer(This->offscreenBuffer);
1391 checkGLcall("glDrawBuffer()");
1396 /*****************************************************************************
1399 * Finds a rendering context and drawable matching the device and render
1400 * target for the current thread, activates them and puts them into the
1404 * This: Device to activate the context for
1405 * target: Requested render target
1406 * usage: Prepares the context for blitting, drawing or other actions
1408 *****************************************************************************/
1409 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1410 DWORD tid = GetCurrentThreadId();
1412 DWORD dirtyState, idx;
1414 WineD3DContext *context;
1415 const struct StateEntry *StateTable = This->StateTable;
1417 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1418 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1419 context = FindContext(This, target, tid);
1420 context->draw_buffer_dirty = TRUE;
1421 This->lastActiveRenderTarget = target;
1422 This->lastThread = tid;
1424 /* Stick to the old context */
1425 context = This->activeContext;
1428 /* Activate the opengl context */
1429 if(last_device != This || context != This->activeContext) {
1432 /* Prevent an unneeded context switch as those are expensive */
1433 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1434 TRACE("Already using gl context %p\n", context->glCtx);
1437 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1439 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1440 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1442 ERR("Failed to activate the new context\n");
1443 } else if(!context->last_was_blit) {
1444 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1447 if(This->activeContext->vshader_const_dirty) {
1448 memset(This->activeContext->vshader_const_dirty, 1,
1449 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1451 if(This->activeContext->pshader_const_dirty) {
1452 memset(This->activeContext->pshader_const_dirty, 1,
1453 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1455 This->activeContext = context;
1459 /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
1463 case CTXUSAGE_CLEAR:
1464 case CTXUSAGE_DRAWPRIM:
1465 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1466 context_apply_fbo_state((IWineD3DDevice *)This);
1468 if (context->draw_buffer_dirty) {
1469 apply_draw_buffer(This, target, FALSE);
1470 context->draw_buffer_dirty = FALSE;
1475 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1476 if (This->render_offscreen) {
1477 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1478 context_bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1479 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1480 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0));
1481 checkGLcall("glFramebufferRenderbufferEXT");
1483 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1484 checkGLcall("glFramebufferRenderbufferEXT");
1486 context->draw_buffer_dirty = TRUE;
1488 if (context->draw_buffer_dirty) {
1489 apply_draw_buffer(This, target, TRUE);
1490 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1491 context->draw_buffer_dirty = FALSE;
1501 case CTXUSAGE_RESOURCELOAD:
1502 /* This does not require any special states to be set up */
1505 case CTXUSAGE_CLEAR:
1506 if(context->last_was_blit) {
1507 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1510 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1511 * blending when clearing improves the clearing performance incredibly.
1513 glDisable(GL_BLEND);
1514 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1516 glEnable(GL_SCISSOR_TEST);
1517 checkGLcall("glEnable GL_SCISSOR_TEST");
1518 context->last_was_blit = FALSE;
1519 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1520 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1523 case CTXUSAGE_DRAWPRIM:
1524 /* This needs all dirty states applied */
1525 if(context->last_was_blit) {
1526 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1529 IWineD3DDeviceImpl_FindTexUnitMap(This);
1531 for(i=0; i < context->numDirtyEntries; i++) {
1532 dirtyState = context->dirtyArray[i];
1533 idx = dirtyState >> 5;
1534 shift = dirtyState & 0x1f;
1535 context->isStateDirty[idx] &= ~(1 << shift);
1536 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1538 context->numDirtyEntries = 0; /* This makes the whole list clean */
1539 context->last_was_blit = FALSE;
1543 SetupForBlit(This, context,
1544 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1545 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1549 FIXME("Unexpected context usage requested\n");