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_clean_fbo_attachments(IWineD3DDeviceImpl *This)
60 for (i = 0; i < GL_LIMITS(buffers); ++i)
62 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, 0, 0));
63 checkGLcall("glFramebufferTexture2D()");
65 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
66 checkGLcall("glFramebufferTexture2D()");
69 static void context_destroy_fbo(IWineD3DDeviceImpl *This, const GLuint *fbo)
71 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, *fbo));
72 checkGLcall("glBindFramebuffer()");
74 context_clean_fbo_attachments(This);
76 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
77 checkGLcall("glBindFramebuffer()");
78 GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo));
79 checkGLcall("glDeleteFramebuffers()");
82 static void context_apply_attachment_filter_states(IWineD3DDevice *iface, IWineD3DSurface *surface, BOOL force_preload)
84 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
85 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
86 IWineD3DBaseTextureImpl *texture_impl;
87 BOOL update_minfilter = FALSE;
88 BOOL update_magfilter = FALSE;
90 /* Update base texture states array */
91 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
93 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
94 || texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
96 texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
97 texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
98 update_minfilter = TRUE;
101 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
103 texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
104 update_magfilter = TRUE;
107 if (texture_impl->baseTexture.bindCount)
109 WARN("Render targets should not be bound to a sampler\n");
110 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(texture_impl->baseTexture.sampler));
113 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
116 if (update_minfilter || update_magfilter || force_preload)
118 GLenum target, bind_target;
121 target = surface_impl->glDescription.target;
122 if (target == GL_TEXTURE_2D)
124 bind_target = GL_TEXTURE_2D;
125 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
126 } else if (target == GL_TEXTURE_RECTANGLE_ARB) {
127 bind_target = GL_TEXTURE_RECTANGLE_ARB;
128 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
130 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
131 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
134 surface_internal_preload(surface, SRGB_RGB);
136 glBindTexture(bind_target, surface_impl->glDescription.textureName);
137 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
138 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
139 glBindTexture(bind_target, old_binding);
142 checkGLcall("apply_attachment_filter_states()");
145 /* TODO: Handle stencil attachments */
146 void context_attach_depth_stencil_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
148 IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
150 TRACE("Attach depth stencil %p\n", depth_stencil);
154 if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
156 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
157 checkGLcall("glFramebufferRenderbufferEXT()");
159 context_apply_attachment_filter_states((IWineD3DDevice *)This, depth_stencil, TRUE);
161 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, depth_stencil_impl->glDescription.target,
162 depth_stencil_impl->glDescription.textureName, depth_stencil_impl->glDescription.level));
163 checkGLcall("glFramebufferTexture2DEXT()");
166 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
167 checkGLcall("glFramebufferTexture2DEXT()");
171 void context_attach_surface_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
173 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
175 TRACE("Attach surface %p to %u\n", surface, idx);
179 context_apply_attachment_filter_states((IWineD3DDevice *)This, surface, TRUE);
181 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, surface_impl->glDescription.target,
182 surface_impl->glDescription.textureName, surface_impl->glDescription.level));
183 checkGLcall("glFramebufferTexture2DEXT()");
185 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, GL_TEXTURE_2D, 0, 0));
186 checkGLcall("glFramebufferTexture2DEXT()");
190 static void context_check_fbo_status(IWineD3DDevice *iface)
192 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
195 status = GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
196 if (status == GL_FRAMEBUFFER_COMPLETE_EXT)
198 TRACE("FBO complete\n");
200 IWineD3DSurfaceImpl *attachment;
202 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
204 /* Dump the FBO attachments */
205 for (i = 0; i < GL_LIMITS(buffers); ++i)
207 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->render_targets[i];
210 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
211 i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
212 attachment->pow2Width, attachment->pow2Height);
215 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->depth_stencil;
218 FIXME("\tDepth attachment: (%p) %s %ux%u\n",
219 attachment, debug_d3dformat(attachment->resource.format_desc->format),
220 attachment->pow2Width, attachment->pow2Height);
225 static struct fbo_entry *context_create_fbo_entry(IWineD3DDevice *iface)
227 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
228 struct fbo_entry *entry;
230 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
231 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
232 memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
233 entry->depth_stencil = This->stencilBufferTarget;
234 entry->attached = FALSE;
240 static void context_reuse_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
242 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
244 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, entry->id));
245 checkGLcall("glBindFramebuffer()");
246 context_clean_fbo_attachments(This);
248 memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
249 entry->depth_stencil = This->stencilBufferTarget;
250 entry->attached = FALSE;
253 static void context_destroy_fbo_entry(IWineD3DDeviceImpl *This, struct fbo_entry *entry)
257 TRACE("Destroy FBO %d\n", entry->id);
258 context_destroy_fbo(This, &entry->id);
260 list_remove(&entry->entry);
261 HeapFree(GetProcessHeap(), 0, entry->render_targets);
262 HeapFree(GetProcessHeap(), 0, entry);
266 static struct fbo_entry *context_find_fbo_entry(IWineD3DDevice *iface, WineD3DContext *context)
268 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
269 struct fbo_entry *entry;
271 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
273 if (!memcmp(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets))
274 && entry->depth_stencil == This->stencilBufferTarget)
276 list_remove(&entry->entry);
277 list_add_head(&context->fbo_list, &entry->entry);
282 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
284 entry = context_create_fbo_entry(iface);
285 list_add_head(&context->fbo_list, &entry->entry);
286 ++context->fbo_entry_count;
290 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
291 context_reuse_fbo_entry(iface, entry);
292 list_remove(&entry->entry);
293 list_add_head(&context->fbo_list, &entry->entry);
299 static void context_apply_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
301 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
304 context_bind_fbo(iface, GL_FRAMEBUFFER_EXT, &entry->id);
306 if (!entry->attached)
308 /* Apply render targets */
309 for (i = 0; i < GL_LIMITS(buffers); ++i)
311 IWineD3DSurface *render_target = This->render_targets[i];
312 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, i, render_target);
315 /* Apply depth targets */
316 if (This->stencilBufferTarget) {
317 unsigned int w = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Width;
318 unsigned int h = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Height;
320 surface_set_compatible_renderbuffer(This->stencilBufferTarget, w, h);
322 context_attach_depth_stencil_fbo(This, GL_FRAMEBUFFER_EXT, This->stencilBufferTarget, TRUE);
324 entry->attached = TRUE;
326 for (i = 0; i < GL_LIMITS(buffers); ++i)
328 if (This->render_targets[i])
329 context_apply_attachment_filter_states(iface, This->render_targets[i], FALSE);
331 if (This->stencilBufferTarget)
332 context_apply_attachment_filter_states(iface, This->stencilBufferTarget, FALSE);
335 for (i = 0; i < GL_LIMITS(buffers); ++i)
337 if (This->render_targets[i])
338 This->draw_buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
340 This->draw_buffers[i] = GL_NONE;
344 static void context_apply_fbo_state(IWineD3DDevice *iface)
346 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
347 WineD3DContext *context = This->activeContext;
349 if (This->render_offscreen)
351 context->current_fbo = context_find_fbo_entry(iface, context);
352 context_apply_fbo_entry(iface, context->current_fbo);
354 context->current_fbo = NULL;
355 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
358 context_check_fbo_status(iface);
361 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
363 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
368 case WINED3DRTYPE_SURFACE:
370 for (i = 0; i < This->numContexts; ++i)
372 struct fbo_entry *entry, *entry2;
374 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->contexts[i]->fbo_list, struct fbo_entry, entry)
376 BOOL destroyed = FALSE;
379 for (j = 0; !destroyed && j < GL_LIMITS(buffers); ++j)
381 if (entry->render_targets[j] == (IWineD3DSurface *)resource)
383 context_destroy_fbo_entry(This, entry);
388 if (!destroyed && entry->depth_stencil == (IWineD3DSurface *)resource)
389 context_destroy_fbo_entry(This, entry);
401 /*****************************************************************************
402 * Context_MarkStateDirty
404 * Marks a state in a context dirty. Only one context, opposed to
405 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
409 * context: Context to mark the state dirty in
410 * state: State to mark dirty
411 * StateTable: Pointer to the state table in use(for state grouping)
413 *****************************************************************************/
414 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
415 DWORD rep = StateTable[state].representative;
419 if(!rep || isStateDirty(context, rep)) return;
421 context->dirtyArray[context->numDirtyEntries++] = rep;
424 context->isStateDirty[idx] |= (1 << shift);
427 /*****************************************************************************
430 * Adds a context to the context array. Helper function for CreateContext
432 * This method is not called in performance-critical code paths, only when a
433 * new render target or swapchain is created. Thus performance is not an issue
437 * This: Device to add the context for
438 * hdc: device context
439 * glCtx: WGL context to add
440 * pbuffer: optional pbuffer used with this context
442 *****************************************************************************/
443 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
444 WineD3DContext **oldArray = This->contexts;
447 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
448 if(This->contexts == NULL) {
449 ERR("Unable to grow the context array\n");
450 This->contexts = oldArray;
454 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
457 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
458 if(This->contexts[This->numContexts] == NULL) {
459 ERR("Unable to allocate a new context\n");
460 HeapFree(GetProcessHeap(), 0, This->contexts);
461 This->contexts = oldArray;
465 This->contexts[This->numContexts]->hdc = hdc;
466 This->contexts[This->numContexts]->glCtx = glCtx;
467 This->contexts[This->numContexts]->pbuffer = pbuffer;
468 This->contexts[This->numContexts]->win_handle = win_handle;
469 HeapFree(GetProcessHeap(), 0, oldArray);
471 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
473 for(state = 0; state <= STATE_HIGHEST; state++) {
474 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
478 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
479 return This->contexts[This->numContexts - 1];
482 /* This function takes care of WineD3D pixel format selection. */
483 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
484 const struct GlPixelFormatDesc *color_format_desc, const struct GlPixelFormatDesc *ds_format_desc,
485 BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
488 unsigned int matchtry;
489 short redBits, greenBits, blueBits, alphaBits, colorBits;
490 short depthBits=0, stencilBits=0;
497 /* First, try without alpha match buffers. MacOS supports aux buffers only
498 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
499 * Then try without aux buffers - this is the most common cause for not
500 * finding a pixel format. Also some drivers(the open source ones)
501 * only offer 32 bit ARB pixel formats. First try without an exact alpha
502 * match, then try without an exact alpha and color match.
504 { TRUE, TRUE, TRUE },
505 { TRUE, FALSE, TRUE },
506 { FALSE, TRUE, TRUE },
507 { FALSE, FALSE, TRUE },
508 { TRUE, FALSE, FALSE },
509 { FALSE, FALSE, FALSE },
513 int nCfgs = This->adapter->nCfgs;
515 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
516 debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
517 auxBuffers, numSamples, pbuffer, findCompatible);
519 if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
521 ERR("Unable to get color bits for format %s (%#x)!\n",
522 debug_d3dformat(color_format_desc->format), color_format_desc->format);
526 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
527 * You are able to add a depth + stencil surface at a later stage when you need it.
528 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
529 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
530 * context, need torecreate shaders, textures and other resources.
532 * The context manager already takes care of the state problem and for the other tasks code from Reset
533 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
534 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
535 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
536 * issue needs to be fixed. */
537 if (ds_format_desc->format != WINED3DFMT_D24S8)
539 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
540 ds_format_desc = getFormatDescEntry(WINED3DFMT_D24S8, &This->adapter->gl_info);
543 getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
545 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
546 for(i=0; i<nCfgs; i++) {
547 BOOL exactDepthMatch = TRUE;
548 WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
550 /* For now only accept RGBA formats. Perhaps some day we will
551 * allow floating point formats for pbuffers. */
552 if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
555 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
556 if(!pbuffer && !(cfg->windowDrawable && cfg->doubleBuffer))
559 /* We like to have aux buffers in backbuffer mode */
560 if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
563 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
564 if(pbuffer && (!cfg->pbufferDrawable || cfg->doubleBuffer))
567 if(matches[matchtry].exact_color) {
568 if(cfg->redSize != redBits)
570 if(cfg->greenSize != greenBits)
572 if(cfg->blueSize != blueBits)
575 if(cfg->redSize < redBits)
577 if(cfg->greenSize < greenBits)
579 if(cfg->blueSize < blueBits)
582 if(matches[matchtry].exact_alpha) {
583 if(cfg->alphaSize != alphaBits)
586 if(cfg->alphaSize < alphaBits)
590 /* We try to locate a format which matches our requirements exactly. In case of
591 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
592 if(cfg->depthSize < depthBits)
594 else if(cfg->depthSize > depthBits)
595 exactDepthMatch = FALSE;
597 /* In all cases make sure the number of stencil bits matches our requirements
598 * even when we don't need stencil because it could affect performance EXCEPT
599 * on cards which don't offer depth formats without stencil like the i915 drivers
601 if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
604 /* Check multisampling support */
605 if(cfg->numSamples != numSamples)
608 /* When we have passed all the checks then we have found a format which matches our
609 * requirements. Note that we only check for a limit number of capabilities right now,
610 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
611 * can still differ in things like multisampling, stereo, SRGB and other flags.
614 /* Exit the loop as we have found a format :) */
615 if(exactDepthMatch) {
616 iPixelFormat = cfg->iPixelFormat;
618 } else if(!iPixelFormat) {
619 /* In the end we might end up with a format which doesn't exactly match our depth
620 * requirements. Accept the first format we found because formats with higher iPixelFormat
621 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
622 iPixelFormat = cfg->iPixelFormat;
627 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
628 if(!iPixelFormat && !findCompatible) {
629 ERR("Can't find a suitable iPixelFormat\n");
631 } else if(!iPixelFormat) {
632 PIXELFORMATDESCRIPTOR pfd;
634 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
635 /* PixelFormat selection */
636 ZeroMemory(&pfd, sizeof(pfd));
637 pfd.nSize = sizeof(pfd);
639 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
640 pfd.iPixelType = PFD_TYPE_RGBA;
641 pfd.cAlphaBits = alphaBits;
642 pfd.cColorBits = colorBits;
643 pfd.cDepthBits = depthBits;
644 pfd.cStencilBits = stencilBits;
645 pfd.iLayerType = PFD_MAIN_PLANE;
647 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
649 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
650 ERR("Can't find a suitable iPixelFormat\n");
655 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
656 iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
660 /*****************************************************************************
663 * Creates a new context for a window, or a pbuffer context.
666 * This: Device to activate the context for
667 * target: Surface this context will render to
668 * win_handle: handle to the window which we are drawing to
669 * create_pbuffer: tells whether to create a pbuffer or not
670 * pPresentParameters: contains the pixelformats to use for onscreen rendering
672 *****************************************************************************/
673 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
674 HDC oldDrawable, hdc;
675 HPBUFFERARB pbuffer = NULL;
676 HGLRC ctx = NULL, oldCtx;
677 WineD3DContext *ret = NULL;
680 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
683 HDC hdc_parent = GetDC(win_handle);
684 int iPixelFormat = 0;
686 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
687 const struct GlPixelFormatDesc *ds_format_desc = StencilSurface
688 ? ((IWineD3DSurfaceImpl *)StencilSurface)->resource.format_desc
689 : getFormatDescEntry(WINED3DFMT_UNKNOWN, &This->adapter->gl_info);
691 /* Try to find a pixel format with pbuffer support. */
692 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
693 ds_format_desc, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */,
694 FALSE /* findCompatible */);
696 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
698 /* For some reason we weren't able to find a format, try to find something instead of crashing.
699 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
700 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
701 ds_format_desc, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */,
702 TRUE /* findCompatible */);
705 /* This shouldn't happen as ChoosePixelFormat always returns something */
707 ERR("Unable to locate a pixel format for a pbuffer\n");
708 ReleaseDC(win_handle, hdc_parent);
712 TRACE("Creating a pBuffer drawable for the new context\n");
713 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
715 ERR("Cannot create a pbuffer\n");
716 ReleaseDC(win_handle, hdc_parent);
720 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
721 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
723 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
724 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
725 ReleaseDC(win_handle, hdc_parent);
728 ReleaseDC(win_handle, hdc_parent);
730 PIXELFORMATDESCRIPTOR pfd;
733 const struct GlPixelFormatDesc *color_format_desc = target->resource.format_desc;
734 const struct GlPixelFormatDesc *ds_format_desc = getFormatDescEntry(WINED3DFMT_UNKNOWN,
735 &This->adapter->gl_info);
736 BOOL auxBuffers = FALSE;
739 hdc = GetDC(win_handle);
741 ERR("Cannot retrieve a device context!\n");
745 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
746 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
749 if (color_format_desc->format == WINED3DFMT_X4R4G4B4)
750 color_format_desc = getFormatDescEntry(WINED3DFMT_A4R4G4B4, &This->adapter->gl_info);
751 else if (color_format_desc->format == WINED3DFMT_X8R8G8B8)
752 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
755 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
756 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
757 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
758 * a format with 8bit alpha, so request A8R8G8B8. */
759 if (color_format_desc->format == WINED3DFMT_P8)
760 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
762 /* Retrieve the depth stencil format from the present parameters.
763 * The choice of the proper format can give a nice performance boost
764 * in case of GPU limited programs. */
765 if(pPresentParms->EnableAutoDepthStencil) {
766 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
767 ds_format_desc = getFormatDescEntry(pPresentParms->AutoDepthStencilFormat, &This->adapter->gl_info);
770 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
771 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
772 if(!GL_SUPPORT(ARB_MULTISAMPLE))
773 ERR("The program is requesting multisampling without support!\n");
775 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
776 numSamples = pPresentParms->MultiSampleType;
780 /* Try to find a pixel format which matches our requirements */
781 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
782 auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
784 /* Try to locate a compatible format if we weren't able to find anything */
786 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
787 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
788 auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
791 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
793 ERR("Can't find a suitable iPixelFormat\n");
797 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
798 res = SetPixelFormat(hdc, iPixelFormat, NULL);
800 int oldPixelFormat = GetPixelFormat(hdc);
802 /* By default WGL doesn't allow pixel format adjustments but we need it here.
803 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
804 * set the pixel format multiple times. Only use it when it is really needed. */
806 if(oldPixelFormat == iPixelFormat) {
807 /* We don't have to do anything as the formats are the same :) */
808 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
809 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
812 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
815 } else if(oldPixelFormat) {
816 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
817 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
818 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
820 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
826 ctx = pwglCreateContext(hdc);
827 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
830 ERR("Failed to create a WGL context\n");
832 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
833 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
837 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
839 ERR("Failed to add the newly created context to the context list\n");
840 pwglDeleteContext(ctx);
842 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
843 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
847 ret->surface = (IWineD3DSurface *) target;
848 ret->isPBuffer = create_pbuffer;
849 ret->tid = GetCurrentThreadId();
850 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
851 /* Create the dirty constants array and initialize them to dirty */
852 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
853 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
854 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
855 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
856 memset(ret->vshader_const_dirty, 1,
857 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
858 memset(ret->pshader_const_dirty, 1,
859 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
862 TRACE("Successfully created new context %p\n", ret);
864 list_init(&ret->fbo_list);
866 /* Set up the context defaults */
867 oldCtx = pwglGetCurrentContext();
868 oldDrawable = pwglGetCurrentDC();
869 if(oldCtx && oldDrawable) {
870 /* See comment in ActivateContext context switching */
871 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
873 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
874 ERR("Cannot activate context to set up defaults\n");
880 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
882 TRACE("Setting up the screen\n");
883 /* Clear the screen */
884 glClearColor(1.0, 0.0, 0.0, 0.0);
885 checkGLcall("glClearColor");
888 glClearStencil(0xffff);
890 checkGLcall("glClear");
892 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
893 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
895 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
896 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
898 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
899 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
901 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
902 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
903 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
904 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
906 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
907 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
908 * and textures in DIB sections(due to the memory protection).
910 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
911 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
913 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
914 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
915 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
916 * GL_VERTEX_BLEND_ARB isn't enabled too
918 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
919 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
921 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
922 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
923 * the previous texture where to source the offset from is always unit - 1.
925 for(s = 1; s < GL_LIMITS(textures); s++) {
926 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
927 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
928 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
932 for(s = 0; s < GL_LIMITS(point_sprite_units); s++) {
933 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
934 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
935 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
939 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
940 * but enable it for the first context we create, and reenable it on the old context
942 if(oldDrawable && oldCtx) {
943 pwglMakeCurrent(oldDrawable, oldCtx);
947 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
955 /*****************************************************************************
956 * RemoveContextFromArray
958 * Removes a context from the context manager. The opengl context is not
959 * destroyed or unset. context is not a valid pointer after that call.
961 * Similar to the former call this isn't a performance critical function. A
962 * helper function for DestroyContext.
965 * This: Device to activate the context for
966 * context: Context to remove
968 *****************************************************************************/
969 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
970 WineD3DContext **new_array;
974 TRACE("Removing ctx %p\n", context);
976 for (i = 0; i < This->numContexts; ++i)
978 if (This->contexts[i] == context)
980 HeapFree(GetProcessHeap(), 0, context);
988 ERR("Context %p doesn't exist in context array\n", context);
992 while (i < This->numContexts - 1)
994 This->contexts[i] = This->contexts[i + 1];
999 if (!This->numContexts)
1001 HeapFree(GetProcessHeap(), 0, This->contexts);
1002 This->contexts = NULL;
1006 new_array = HeapReAlloc(GetProcessHeap(), 0, This->contexts, This->numContexts * sizeof(*This->contexts));
1009 ERR("Failed to shrink context array. Oh well.\n");
1013 This->contexts = new_array;
1016 /*****************************************************************************
1019 * Destroys a wineD3DContext
1022 * This: Device to activate the context for
1023 * context: Context to destroy
1025 *****************************************************************************/
1026 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
1027 struct fbo_entry *entry, *entry2;
1029 TRACE("Destroying ctx %p\n", context);
1031 /* The correct GL context needs to be active to cleanup the GL resources below */
1032 if(pwglGetCurrentContext() != context->glCtx){
1033 pwglMakeCurrent(context->hdc, context->glCtx);
1039 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
1040 context_destroy_fbo_entry(This, entry);
1042 if (context->src_fbo) {
1043 TRACE("Destroy src FBO %d\n", context->src_fbo);
1044 context_destroy_fbo(This, &context->src_fbo);
1046 if (context->dst_fbo) {
1047 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
1048 context_destroy_fbo(This, &context->dst_fbo);
1053 if (This->activeContext == context)
1055 This->activeContext = NULL;
1056 TRACE("Destroying the active context.\n");
1059 /* Cleanup the GL context */
1060 pwglMakeCurrent(NULL, NULL);
1061 if(context->isPBuffer) {
1062 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
1063 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
1064 } else ReleaseDC(context->win_handle, context->hdc);
1065 pwglDeleteContext(context->glCtx);
1067 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1068 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1069 RemoveContextFromArray(This, context);
1072 static inline void set_blit_dimension(UINT width, UINT height) {
1073 glMatrixMode(GL_PROJECTION);
1074 checkGLcall("glMatrixMode(GL_PROJECTION)");
1076 checkGLcall("glLoadIdentity()");
1077 glOrtho(0, width, height, 0, 0.0, -1.0);
1078 checkGLcall("glOrtho");
1079 glViewport(0, 0, width, height);
1080 checkGLcall("glViewport");
1083 /*****************************************************************************
1086 * Sets up a context for DirectDraw blitting.
1087 * All texture units are disabled, texture unit 0 is set as current unit
1088 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1089 * color writing enabled for all channels
1090 * register combiners disabled, shaders disabled
1091 * world matrix is set to identity, texture matrix 0 too
1092 * projection matrix is setup for drawing screen coordinates
1095 * This: Device to activate the context for
1096 * context: Context to setup
1097 * width: render target width
1098 * height: render target height
1100 *****************************************************************************/
1101 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
1103 const struct StateEntry *StateTable = This->StateTable;
1105 TRACE("Setting up context %p for blitting\n", context);
1106 if(context->last_was_blit) {
1107 if(context->blit_w != width || context->blit_h != height) {
1108 set_blit_dimension(width, height);
1109 context->blit_w = width; context->blit_h = height;
1110 /* No need to dirtify here, the states are still dirtified because they weren't
1111 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1115 TRACE("Context is already set up for blitting, nothing to do\n");
1118 context->last_was_blit = TRUE;
1120 /* TODO: Use a display list */
1122 /* Disable shaders */
1123 This->shader_backend->shader_select((IWineD3DDevice *)This, FALSE, FALSE);
1124 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1125 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1127 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1128 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1129 * which can safely be called from here, we only lock once instead locking/unlocking
1130 * after each GL call.
1134 /* Disable all textures. The caller can then bind a texture it wants to blit
1137 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1138 * function texture unit. No need to care for higher samplers
1140 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
1141 sampler = This->rev_tex_unit_map[i];
1142 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1143 checkGLcall("glActiveTextureARB");
1145 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1146 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1147 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1149 glDisable(GL_TEXTURE_3D);
1150 checkGLcall("glDisable GL_TEXTURE_3D");
1151 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1152 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1153 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1155 glDisable(GL_TEXTURE_2D);
1156 checkGLcall("glDisable GL_TEXTURE_2D");
1158 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1159 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1161 if (sampler != -1) {
1162 if (sampler < MAX_TEXTURES) {
1163 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1165 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1168 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1169 checkGLcall("glActiveTextureARB");
1171 sampler = This->rev_tex_unit_map[0];
1173 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1174 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1175 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1177 glDisable(GL_TEXTURE_3D);
1178 checkGLcall("glDisable GL_TEXTURE_3D");
1179 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1180 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1181 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1183 glDisable(GL_TEXTURE_2D);
1184 checkGLcall("glDisable GL_TEXTURE_2D");
1186 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1188 glMatrixMode(GL_TEXTURE);
1189 checkGLcall("glMatrixMode(GL_TEXTURE)");
1191 checkGLcall("glLoadIdentity()");
1193 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
1194 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1195 GL_TEXTURE_LOD_BIAS_EXT,
1197 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1200 if (sampler != -1) {
1201 if (sampler < MAX_TEXTURES) {
1202 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1203 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1205 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1208 /* Other misc states */
1209 glDisable(GL_ALPHA_TEST);
1210 checkGLcall("glDisable(GL_ALPHA_TEST)");
1211 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1212 glDisable(GL_LIGHTING);
1213 checkGLcall("glDisable GL_LIGHTING");
1214 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1215 glDisable(GL_DEPTH_TEST);
1216 checkGLcall("glDisable GL_DEPTH_TEST");
1217 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1218 glDisableWINE(GL_FOG);
1219 checkGLcall("glDisable GL_FOG");
1220 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1221 glDisable(GL_BLEND);
1222 checkGLcall("glDisable GL_BLEND");
1223 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1224 glDisable(GL_CULL_FACE);
1225 checkGLcall("glDisable GL_CULL_FACE");
1226 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1227 glDisable(GL_STENCIL_TEST);
1228 checkGLcall("glDisable GL_STENCIL_TEST");
1229 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1230 glDisable(GL_SCISSOR_TEST);
1231 checkGLcall("glDisable GL_SCISSOR_TEST");
1232 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1233 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
1234 glDisable(GL_POINT_SPRITE_ARB);
1235 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1236 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1238 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1239 checkGLcall("glColorMask");
1240 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1241 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
1242 glDisable(GL_COLOR_SUM_EXT);
1243 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1244 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1247 /* Setup transforms */
1248 glMatrixMode(GL_MODELVIEW);
1249 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1251 checkGLcall("glLoadIdentity()");
1252 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1254 context->last_was_rhw = TRUE;
1255 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1257 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1258 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1259 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1260 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1261 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1262 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1263 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1266 set_blit_dimension(width, height);
1267 context->blit_w = width; context->blit_h = height;
1268 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1269 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1272 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1275 /*****************************************************************************
1276 * findThreadContextForSwapChain
1278 * Searches a swapchain for all contexts and picks one for the thread tid.
1279 * If none can be found the swapchain is requested to create a new context
1281 *****************************************************************************/
1282 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
1285 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1286 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1287 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1292 /* Create a new context for the thread */
1293 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
1296 /*****************************************************************************
1299 * Finds a context for the current render target and thread
1302 * target: Render target to find the context for
1303 * tid: Thread to activate the context for
1305 * Returns: The needed context
1307 *****************************************************************************/
1308 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
1309 IWineD3DSwapChain *swapchain = NULL;
1310 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
1311 WineD3DContext *context = This->activeContext;
1312 BOOL oldRenderOffscreen = This->render_offscreen;
1313 const struct GlPixelFormatDesc *old = ((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->resource.format_desc;
1314 const struct GlPixelFormatDesc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
1315 const struct StateEntry *StateTable = This->StateTable;
1317 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1318 * the alpha blend state changes with different render target formats
1320 if (old->format != new->format)
1322 /* Disable blending when the alpha mask has changed and when a format doesn't support blending */
1323 if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
1324 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
1326 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1330 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1331 TRACE("Rendering onscreen\n");
1333 context = findThreadContextForSwapChain(swapchain, tid);
1335 This->render_offscreen = FALSE;
1336 /* The context != This->activeContext will catch a NOP context change. This can occur
1337 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1338 * rendering. No context change is needed in that case
1341 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1342 if(This->pbufferContext && tid == This->pbufferContext->tid) {
1343 This->pbufferContext->tid = 0;
1346 IWineD3DSwapChain_Release(swapchain);
1348 if(oldRenderOffscreen) {
1349 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1350 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1351 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1352 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1353 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1357 TRACE("Rendering offscreen\n");
1358 This->render_offscreen = TRUE;
1360 switch(wined3d_settings.offscreen_rendering_mode) {
1362 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1363 if(This->activeContext && tid == This->lastThread) {
1364 context = This->activeContext;
1366 /* This may happen if the app jumps straight into offscreen rendering
1367 * Start using the context of the primary swapchain. tid == 0 is no problem
1368 * for findThreadContextForSwapChain.
1370 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1371 * is perfect to call.
1373 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1379 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
1380 if(This->pbufferContext == NULL ||
1381 This->pbufferWidth < targetimpl->currentDesc.Width ||
1382 This->pbufferHeight < targetimpl->currentDesc.Height) {
1383 if(This->pbufferContext) {
1384 DestroyContext(This, This->pbufferContext);
1387 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1388 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1390 This->pbufferContext = CreateContext(This, targetimpl,
1391 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1392 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1393 This->pbufferWidth = targetimpl->currentDesc.Width;
1394 This->pbufferHeight = targetimpl->currentDesc.Height;
1397 if(This->pbufferContext) {
1398 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1399 FIXME("The PBuffr context is only supported for one thread for now!\n");
1401 This->pbufferContext->tid = tid;
1402 context = This->pbufferContext;
1405 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1406 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1410 case ORM_BACKBUFFER:
1411 /* Stay with the currently active context for back buffer rendering */
1412 if(This->activeContext && tid == This->lastThread) {
1413 context = This->activeContext;
1415 /* This may happen if the app jumps straight into offscreen rendering
1416 * Start using the context of the primary swapchain. tid == 0 is no problem
1417 * for findThreadContextForSwapChain.
1419 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1420 * is perfect to call.
1422 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1427 if(!oldRenderOffscreen) {
1428 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1429 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1430 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1431 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1432 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1436 /* When switching away from an offscreen render target, and we're not using FBOs,
1437 * we have to read the drawable into the texture. This is done via PreLoad(and
1438 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1439 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1440 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1441 * is read. This leads to these possible situations:
1443 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1444 * Nothing to do, we don't even reach this code in this case...
1446 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1447 * The currently active context is OK for readback. Call PreLoad, and it
1450 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1451 * Nothing to do - the drawable is unchanged
1453 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1454 * This is tricky. We have to get a context with the old drawable from somewhere
1455 * before we can switch to the new context. In this case, PreLoad calls
1456 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1457 * is case (2) then. The old drawable is activated for the new thread, and the
1458 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1459 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1460 * target for the new thread
1462 if (readTexture && This->lastActiveRenderTarget != target) {
1463 BOOL oldInDraw = This->isInDraw;
1465 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1466 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1467 * when using offscreen rendering with multithreading
1469 This->isInDraw = TRUE;
1471 /* Do that before switching the context:
1472 * Read the back buffer of the old drawable into the destination texture
1474 if(((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->glDescription.srgbTextureName) {
1475 surface_internal_preload(This->lastActiveRenderTarget, SRGB_BOTH);
1477 surface_internal_preload(This->lastActiveRenderTarget, SRGB_RGB);
1480 /* Assume that the drawable will be modified by some other things now */
1481 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1483 This->isInDraw = oldInDraw;
1489 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1491 IWineD3DSwapChain *swapchain;
1493 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain)))
1495 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1497 glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1498 checkGLcall("glDrawBuffers()");
1504 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1508 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1510 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1511 checkGLcall("glDrawBuffers()");
1515 glDrawBuffer(This->draw_buffers[0]);
1516 checkGLcall("glDrawBuffer()");
1519 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1520 checkGLcall("glDrawBuffer()");
1525 glDrawBuffer(This->offscreenBuffer);
1526 checkGLcall("glDrawBuffer()");
1532 /*****************************************************************************
1535 * Finds a rendering context and drawable matching the device and render
1536 * target for the current thread, activates them and puts them into the
1540 * This: Device to activate the context for
1541 * target: Requested render target
1542 * usage: Prepares the context for blitting, drawing or other actions
1544 *****************************************************************************/
1545 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1546 DWORD tid = GetCurrentThreadId();
1547 DWORD i, dirtyState, idx;
1549 WineD3DContext *context;
1550 const struct StateEntry *StateTable = This->StateTable;
1552 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1553 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1554 context = FindContext(This, target, tid);
1555 context->draw_buffer_dirty = TRUE;
1556 This->lastActiveRenderTarget = target;
1557 This->lastThread = tid;
1559 /* Stick to the old context */
1560 context = This->activeContext;
1563 /* Activate the opengl context */
1564 if(last_device != This || context != This->activeContext) {
1567 /* Prevent an unneeded context switch as those are expensive */
1568 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1569 TRACE("Already using gl context %p\n", context->glCtx);
1572 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1574 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1576 ERR("Failed to activate the new context\n");
1577 } else if(!context->last_was_blit) {
1578 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1580 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1583 if(This->activeContext->vshader_const_dirty) {
1584 memset(This->activeContext->vshader_const_dirty, 1,
1585 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1587 if(This->activeContext->pshader_const_dirty) {
1588 memset(This->activeContext->pshader_const_dirty, 1,
1589 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1591 This->activeContext = context;
1596 case CTXUSAGE_CLEAR:
1597 case CTXUSAGE_DRAWPRIM:
1598 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1599 context_apply_fbo_state((IWineD3DDevice *)This);
1601 if (context->draw_buffer_dirty) {
1602 apply_draw_buffer(This, target, FALSE);
1603 context->draw_buffer_dirty = FALSE;
1608 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1609 if (This->render_offscreen) {
1610 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1611 context_bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1612 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1615 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0));
1616 checkGLcall("glFramebufferRenderbufferEXT");
1620 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1621 checkGLcall("glFramebufferRenderbufferEXT");
1624 context->draw_buffer_dirty = TRUE;
1626 if (context->draw_buffer_dirty) {
1627 apply_draw_buffer(This, target, TRUE);
1628 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1629 context->draw_buffer_dirty = FALSE;
1639 case CTXUSAGE_RESOURCELOAD:
1640 /* This does not require any special states to be set up */
1643 case CTXUSAGE_CLEAR:
1644 if(context->last_was_blit) {
1645 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1648 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1649 * blending when clearing improves the clearing performance incredibly.
1652 glDisable(GL_BLEND);
1654 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1657 glEnable(GL_SCISSOR_TEST);
1658 checkGLcall("glEnable GL_SCISSOR_TEST");
1660 context->last_was_blit = FALSE;
1661 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1662 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1665 case CTXUSAGE_DRAWPRIM:
1666 /* This needs all dirty states applied */
1667 if(context->last_was_blit) {
1668 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1671 IWineD3DDeviceImpl_FindTexUnitMap(This);
1673 for(i=0; i < context->numDirtyEntries; i++) {
1674 dirtyState = context->dirtyArray[i];
1675 idx = dirtyState >> 5;
1676 shift = dirtyState & 0x1f;
1677 context->isStateDirty[idx] &= ~(1 << shift);
1678 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1680 context->numDirtyEntries = 0; /* This makes the whole list clean */
1681 context->last_was_blit = FALSE;
1685 SetupForBlit(This, context,
1686 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1687 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1691 FIXME("Unexpected context usage requested\n");
1695 WineD3DContext *getActiveContext(void) {
1696 return last_device->activeContext;