push a4aeee26091b4888c4962ca8601c7905b237df2d
[wine/hacks.git] / dlls / wined3d / context.c
blobfb3fcc48c109f57d60907fdd9af36fd296e35341
1 /*
2 * Context and render target management in wined3d
4 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include <stdio.h>
23 #ifdef HAVE_FLOAT_H
24 # include <float.h>
25 #endif
26 #include "wined3d_private.h"
28 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
30 #define GLINFO_LOCATION This->adapter->gl_info
32 /* The last used device.
34 * If the application creates multiple devices and switches between them, ActivateContext has to
35 * change the opengl context. This flag allows to keep track which device is active
37 static IWineD3DDeviceImpl *last_device;
39 /*****************************************************************************
40 * Context_MarkStateDirty
42 * Marks a state in a context dirty. Only one context, opposed to
43 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
44 * contexts
46 * Params:
47 * context: Context to mark the state dirty in
48 * state: State to mark dirty
49 * StateTable: Pointer to the state table in use(for state grouping)
51 *****************************************************************************/
52 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
53 DWORD rep = StateTable[state].representative;
54 DWORD idx;
55 BYTE shift;
57 if(!rep || isStateDirty(context, rep)) return;
59 context->dirtyArray[context->numDirtyEntries++] = rep;
60 idx = rep >> 5;
61 shift = rep & 0x1f;
62 context->isStateDirty[idx] |= (1 << shift);
65 /*****************************************************************************
66 * AddContextToArray
68 * Adds a context to the context array. Helper function for CreateContext
70 * This method is not called in performance-critical code paths, only when a
71 * new render target or swapchain is created. Thus performance is not an issue
72 * here.
74 * Params:
75 * This: Device to add the context for
76 * hdc: device context
77 * glCtx: WGL context to add
78 * pbuffer: optional pbuffer used with this context
80 *****************************************************************************/
81 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
82 WineD3DContext **oldArray = This->contexts;
83 DWORD state;
85 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
86 if(This->contexts == NULL) {
87 ERR("Unable to grow the context array\n");
88 This->contexts = oldArray;
89 return NULL;
91 if(oldArray) {
92 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
95 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
96 if(This->contexts[This->numContexts] == NULL) {
97 ERR("Unable to allocate a new context\n");
98 HeapFree(GetProcessHeap(), 0, This->contexts);
99 This->contexts = oldArray;
100 return NULL;
103 This->contexts[This->numContexts]->hdc = hdc;
104 This->contexts[This->numContexts]->glCtx = glCtx;
105 This->contexts[This->numContexts]->pbuffer = pbuffer;
106 This->contexts[This->numContexts]->win_handle = win_handle;
107 HeapFree(GetProcessHeap(), 0, oldArray);
109 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
111 for(state = 0; state <= STATE_HIGHEST; state++) {
112 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
115 This->numContexts++;
116 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
117 return This->contexts[This->numContexts - 1];
120 /* This function takes care of WineD3D pixel format selection. */
121 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc, WINED3DFORMAT ColorFormat, WINED3DFORMAT DepthStencilFormat, BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
123 int iPixelFormat=0, matchtry;
124 short redBits, greenBits, blueBits, alphaBits, colorBits;
125 short depthBits=0, stencilBits=0;
127 struct match_type {
128 BOOL require_aux;
129 BOOL exact_alpha;
130 BOOL exact_color;
131 } matches[] = {
132 /* First, try without alpha match buffers. MacOS supports aux buffers only
133 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
134 * Then try without aux buffers - this is the most common cause for not
135 * finding a pixel format. Also some drivers(the open source ones)
136 * only offer 32 bit ARB pixel formats. First try without an exact alpha
137 * match, then try without an exact alpha and color match.
139 { FALSE, TRUE, TRUE },
140 { TRUE, TRUE, TRUE },
141 { FALSE, FALSE, TRUE },
142 { FALSE, FALSE, FALSE },
143 { TRUE, FALSE, TRUE },
144 { TRUE, FALSE, FALSE },
147 int i = 0;
148 int nCfgs = This->adapter->nCfgs;
149 WineD3D_PixelFormat *cfgs = This->adapter->cfgs;
151 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
152 debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat), auxBuffers, numSamples, pbuffer, findCompatible);
154 if(!getColorBits(ColorFormat, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
155 ERR("Unable to get color bits for format %s (%#x)!\n", debug_d3dformat(ColorFormat), ColorFormat);
156 return 0;
159 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
160 * You are able to add a depth + stencil surface at a later stage when you need it.
161 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
162 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
163 * context, need torecreate shaders, textures and other resources.
165 * The context manager already takes care of the state problem and for the other tasks code from Reset
166 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
167 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
168 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
169 * issue needs to be fixed. */
170 if(DepthStencilFormat != WINED3DFMT_D24S8)
171 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
173 DepthStencilFormat = WINED3DFMT_D24S8;
175 if(DepthStencilFormat) {
176 getDepthStencilBits(DepthStencilFormat, &depthBits, &stencilBits);
179 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
180 for(i=0; i<nCfgs; i++) {
181 BOOL exactDepthMatch = TRUE;
182 cfgs = &This->adapter->cfgs[i];
184 /* For now only accept RGBA formats. Perhaps some day we will
185 * allow floating point formats for pbuffers. */
186 if(cfgs->iPixelType != WGL_TYPE_RGBA_ARB)
187 continue;
189 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
190 if(!pbuffer && !(cfgs->windowDrawable && cfgs->doubleBuffer))
191 continue;
193 /* We like to have aux buffers in backbuffer mode */
194 if(auxBuffers && !cfgs->auxBuffers && matches[matchtry].require_aux)
195 continue;
197 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
198 if(pbuffer && (!cfgs->pbufferDrawable || cfgs->doubleBuffer))
199 continue;
201 if(matches[matchtry].exact_color) {
202 if(cfgs->redSize != redBits)
203 continue;
204 if(cfgs->greenSize != greenBits)
205 continue;
206 if(cfgs->blueSize != blueBits)
207 continue;
208 } else {
209 if(cfgs->redSize < redBits)
210 continue;
211 if(cfgs->greenSize < greenBits)
212 continue;
213 if(cfgs->blueSize < blueBits)
214 continue;
216 if(matches[matchtry].exact_alpha) {
217 if(cfgs->alphaSize != alphaBits)
218 continue;
219 } else {
220 if(cfgs->alphaSize < alphaBits)
221 continue;
224 /* We try to locate a format which matches our requirements exactly. In case of
225 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
226 if(cfgs->depthSize < depthBits)
227 continue;
228 else if(cfgs->depthSize > depthBits)
229 exactDepthMatch = FALSE;
231 /* In all cases make sure the number of stencil bits matches our requirements
232 * even when we don't need stencil because it could affect performance EXCEPT
233 * on cards which don't offer depth formats without stencil like the i915 drivers
234 * on Linux. */
235 if(stencilBits != cfgs->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfgs->stencilSize))
236 continue;
238 /* Check multisampling support */
239 if(cfgs->numSamples != numSamples)
240 continue;
242 /* When we have passed all the checks then we have found a format which matches our
243 * requirements. Note that we only check for a limit number of capabilities right now,
244 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
245 * can still differ in things like multisampling, stereo, SRGB and other flags.
248 /* Exit the loop as we have found a format :) */
249 if(exactDepthMatch) {
250 iPixelFormat = cfgs->iPixelFormat;
251 break;
252 } else if(!iPixelFormat) {
253 /* In the end we might end up with a format which doesn't exactly match our depth
254 * requirements. Accept the first format we found because formats with higher iPixelFormat
255 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
256 iPixelFormat = cfgs->iPixelFormat;
261 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
262 if(!iPixelFormat && !findCompatible) {
263 ERR("Can't find a suitable iPixelFormat\n");
264 return FALSE;
265 } else if(!iPixelFormat) {
266 PIXELFORMATDESCRIPTOR pfd;
268 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
269 /* PixelFormat selection */
270 ZeroMemory(&pfd, sizeof(pfd));
271 pfd.nSize = sizeof(pfd);
272 pfd.nVersion = 1;
273 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
274 pfd.iPixelType = PFD_TYPE_RGBA;
275 pfd.cAlphaBits = alphaBits;
276 pfd.cColorBits = colorBits;
277 pfd.cDepthBits = depthBits;
278 pfd.cStencilBits = stencilBits;
279 pfd.iLayerType = PFD_MAIN_PLANE;
281 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
282 if(!iPixelFormat) {
283 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
284 ERR("Can't find a suitable iPixelFormat\n");
285 return FALSE;
289 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n", iPixelFormat, debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat));
290 return iPixelFormat;
293 /*****************************************************************************
294 * CreateContext
296 * Creates a new context for a window, or a pbuffer context.
298 * * Params:
299 * This: Device to activate the context for
300 * target: Surface this context will render to
301 * win_handle: handle to the window which we are drawing to
302 * create_pbuffer: tells whether to create a pbuffer or not
303 * pPresentParameters: contains the pixelformats to use for onscreen rendering
305 *****************************************************************************/
306 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
307 HDC oldDrawable, hdc;
308 HPBUFFERARB pbuffer = NULL;
309 HGLRC ctx = NULL, oldCtx;
310 WineD3DContext *ret = NULL;
311 int s;
313 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
315 if(create_pbuffer) {
316 HDC hdc_parent = GetDC(win_handle);
317 int iPixelFormat = 0;
319 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
320 WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
322 /* Try to find a pixel format with pbuffer support. */
323 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */, FALSE /* findCompatible */);
324 if(!iPixelFormat) {
325 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
327 /* For some reason we weren't able to find a format, try to find something instead of crashing.
328 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
329 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */, TRUE /* findCompatible */);
332 /* This shouldn't happen as ChoosePixelFormat always returns something */
333 if(!iPixelFormat) {
334 ERR("Unable to locate a pixel format for a pbuffer\n");
335 ReleaseDC(win_handle, hdc_parent);
336 goto out;
339 TRACE("Creating a pBuffer drawable for the new context\n");
340 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
341 if(!pbuffer) {
342 ERR("Cannot create a pbuffer\n");
343 ReleaseDC(win_handle, hdc_parent);
344 goto out;
347 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
348 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
349 if(!hdc) {
350 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
351 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
352 ReleaseDC(win_handle, hdc_parent);
353 goto out;
355 ReleaseDC(win_handle, hdc_parent);
356 } else {
357 PIXELFORMATDESCRIPTOR pfd;
358 int iPixelFormat;
359 int res;
360 WINED3DFORMAT ColorFormat = target->resource.format;
361 WINED3DFORMAT DepthStencilFormat = 0;
362 BOOL auxBuffers = FALSE;
363 int numSamples = 0;
365 hdc = GetDC(win_handle);
366 if(hdc == NULL) {
367 ERR("Cannot retrieve a device context!\n");
368 goto out;
371 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
372 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
373 auxBuffers = TRUE;
375 if(target->resource.format == WINED3DFMT_X4R4G4B4)
376 ColorFormat = WINED3DFMT_A4R4G4B4;
377 else if(target->resource.format == WINED3DFMT_X8R8G8B8)
378 ColorFormat = WINED3DFMT_A8R8G8B8;
381 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
382 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
383 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
384 * a format with 8bit alpha, so request A8R8G8B8. */
385 if(ColorFormat == WINED3DFMT_P8)
386 ColorFormat = WINED3DFMT_A8R8G8B8;
388 /* Retrieve the depth stencil format from the present parameters.
389 * The choice of the proper format can give a nice performance boost
390 * in case of GPU limited programs. */
391 if(pPresentParms->EnableAutoDepthStencil) {
392 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
393 DepthStencilFormat = pPresentParms->AutoDepthStencilFormat;
396 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
397 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
398 if(!GL_SUPPORT(ARB_MULTISAMPLE))
399 ERR("The program is requesting multisampling without support!\n");
400 else {
401 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
402 numSamples = pPresentParms->MultiSampleType;
406 /* Try to find a pixel format which matches our requirements */
407 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
409 /* Try to locate a compatible format if we weren't able to find anything */
410 if(!iPixelFormat) {
411 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
412 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
415 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
416 if(!iPixelFormat) {
417 ERR("Can't find a suitable iPixelFormat\n");
418 return FALSE;
421 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
422 res = SetPixelFormat(hdc, iPixelFormat, NULL);
423 if(!res) {
424 int oldPixelFormat = GetPixelFormat(hdc);
426 /* By default WGL doesn't allow pixel format adjustments but we need it here.
427 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
428 * set the pixel format multiple times. Only use it when it is really needed. */
430 if(oldPixelFormat == iPixelFormat) {
431 /* We don't have to do anything as the formats are the same :) */
432 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
433 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
435 if(!res) {
436 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
437 return FALSE;
439 } else if(oldPixelFormat) {
440 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
441 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
442 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
443 } else {
444 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
445 return FALSE;
450 ctx = pwglCreateContext(hdc);
451 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
453 if(!ctx) {
454 ERR("Failed to create a WGL context\n");
455 if(create_pbuffer) {
456 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
457 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
459 goto out;
461 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
462 if(!ret) {
463 ERR("Failed to add the newly created context to the context list\n");
464 pwglDeleteContext(ctx);
465 if(create_pbuffer) {
466 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
467 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
469 goto out;
471 ret->surface = (IWineD3DSurface *) target;
472 ret->isPBuffer = create_pbuffer;
473 ret->tid = GetCurrentThreadId();
474 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
475 /* Create the dirty constants array and initialize them to dirty */
476 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
477 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
478 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
479 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
480 memset(ret->vshader_const_dirty, 1,
481 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
482 memset(ret->pshader_const_dirty, 1,
483 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
486 TRACE("Successfully created new context %p\n", ret);
488 ret->fbo_color_attachments = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IWineD3DSurface *) * GL_LIMITS(buffers));
489 if (!ret->fbo_color_attachments)
491 ERR("Out of memory!\n");
492 goto out;
495 /* Set up the context defaults */
496 oldCtx = pwglGetCurrentContext();
497 oldDrawable = pwglGetCurrentDC();
498 if(oldCtx && oldDrawable) {
499 /* See comment in ActivateContext context switching */
500 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
502 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
503 ERR("Cannot activate context to set up defaults\n");
504 goto out;
507 ENTER_GL();
509 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
511 TRACE("Setting up the screen\n");
512 /* Clear the screen */
513 glClearColor(1.0, 0.0, 0.0, 0.0);
514 checkGLcall("glClearColor");
515 glClearIndex(0);
516 glClearDepth(1);
517 glClearStencil(0xffff);
519 checkGLcall("glClear");
521 glColor3f(1.0, 1.0, 1.0);
522 checkGLcall("glColor3f");
524 glEnable(GL_LIGHTING);
525 checkGLcall("glEnable");
527 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
528 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
530 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
531 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
533 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
534 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
536 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
537 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
538 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
539 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
541 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
542 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
543 * and textures in DIB sections(due to the memory protection).
545 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
546 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
548 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
549 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
550 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
551 * GL_VERTEX_BLEND_ARB isn't enabled too
553 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
554 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
556 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
557 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
558 * the previous texture where to source the offset from is always unit - 1.
560 for(s = 1; s < GL_LIMITS(textures); s++) {
561 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
562 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
563 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
567 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
568 for(s = 0; s < GL_LIMITS(textures); s++) {
569 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
570 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
571 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
574 LEAVE_GL();
576 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
577 * but enable it for the first context we create, and reenable it on the old context
579 if(oldDrawable && oldCtx) {
580 pwglMakeCurrent(oldDrawable, oldCtx);
581 } else {
582 last_device = This;
584 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
586 return ret;
588 out:
589 HeapFree(GetProcessHeap(), 0, ret->fbo_color_attachments);
590 return NULL;
593 /*****************************************************************************
594 * RemoveContextFromArray
596 * Removes a context from the context manager. The opengl context is not
597 * destroyed or unset. context is not a valid pointer after that call.
599 * Similar to the former call this isn't a performance critical function. A
600 * helper function for DestroyContext.
602 * Params:
603 * This: Device to activate the context for
604 * context: Context to remove
606 *****************************************************************************/
607 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
608 UINT t, s;
609 WineD3DContext **oldArray = This->contexts;
611 TRACE("Removing ctx %p\n", context);
613 This->numContexts--;
615 if(This->numContexts) {
616 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
617 if(!This->contexts) {
618 ERR("Cannot allocate a new context array, PANIC!!!\n");
620 t = 0;
621 /* Note that we decreased numContexts a few lines up, so use '<=' instead of '<' */
622 for(s = 0; s <= This->numContexts; s++) {
623 if(oldArray[s] == context) continue;
624 This->contexts[t] = oldArray[s];
625 t++;
627 } else {
628 This->contexts = NULL;
631 HeapFree(GetProcessHeap(), 0, context);
632 HeapFree(GetProcessHeap(), 0, oldArray);
635 /*****************************************************************************
636 * DestroyContext
638 * Destroys a wineD3DContext
640 * Params:
641 * This: Device to activate the context for
642 * context: Context to destroy
644 *****************************************************************************/
645 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
647 TRACE("Destroying ctx %p\n", context);
649 /* The correct GL context needs to be active to cleanup the GL resources below */
650 if(pwglGetCurrentContext() != context->glCtx){
651 pwglMakeCurrent(context->hdc, context->glCtx);
652 last_device = NULL;
655 ENTER_GL();
657 if (context->fbo) {
658 GL_EXTCALL(glDeleteFramebuffersEXT(1, &context->fbo));
660 if (context->src_fbo) {
661 GL_EXTCALL(glDeleteFramebuffersEXT(1, &context->src_fbo));
663 if (context->dst_fbo) {
664 GL_EXTCALL(glDeleteFramebuffersEXT(1, &context->dst_fbo));
667 LEAVE_GL();
669 HeapFree(GetProcessHeap(), 0, context->fbo_color_attachments);
670 context->fbo_color_attachments = NULL;
672 /* Cleanup the GL context */
673 pwglMakeCurrent(NULL, NULL);
674 if(context->isPBuffer) {
675 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
676 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
677 } else ReleaseDC(context->win_handle, context->hdc);
678 pwglDeleteContext(context->glCtx);
680 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
681 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
682 RemoveContextFromArray(This, context);
685 static inline void set_blit_dimension(UINT width, UINT height) {
686 glMatrixMode(GL_PROJECTION);
687 checkGLcall("glMatrixMode(GL_PROJECTION)");
688 glLoadIdentity();
689 checkGLcall("glLoadIdentity()");
690 glOrtho(0, width, height, 0, 0.0, -1.0);
691 checkGLcall("glOrtho");
692 glViewport(0, 0, width, height);
693 checkGLcall("glViewport");
696 /*****************************************************************************
697 * SetupForBlit
699 * Sets up a context for DirectDraw blitting.
700 * All texture units are disabled, texture unit 0 is set as current unit
701 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
702 * color writing enabled for all channels
703 * register combiners disabled, shaders disabled
704 * world matrix is set to identity, texture matrix 0 too
705 * projection matrix is setup for drawing screen coordinates
707 * Params:
708 * This: Device to activate the context for
709 * context: Context to setup
710 * width: render target width
711 * height: render target height
713 *****************************************************************************/
714 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
715 int i, sampler;
716 const struct StateEntry *StateTable = This->StateTable;
718 TRACE("Setting up context %p for blitting\n", context);
719 if(context->last_was_blit) {
720 if(context->blit_w != width || context->blit_h != height) {
721 set_blit_dimension(width, height);
722 context->blit_w = width; context->blit_h = height;
723 /* No need to dirtify here, the states are still dirtified because they weren't
724 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
725 * be set
728 TRACE("Context is already set up for blitting, nothing to do\n");
729 return;
731 context->last_was_blit = TRUE;
733 /* TODO: Use a display list */
735 /* Disable shaders */
736 This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
737 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
738 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
740 /* Disable all textures. The caller can then bind a texture it wants to blit
741 * from
743 if(GL_SUPPORT(NV_REGISTER_COMBINERS)) {
744 glDisable(GL_REGISTER_COMBINERS_NV);
745 checkGLcall("glDisable(GL_REGISTER_COMBINERS_NV)");
747 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
748 /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
749 * function texture unit. No need to care for higher samplers
751 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
752 sampler = This->rev_tex_unit_map[i];
753 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
754 checkGLcall("glActiveTextureARB");
756 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
757 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
758 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
760 glDisable(GL_TEXTURE_3D);
761 checkGLcall("glDisable GL_TEXTURE_3D");
762 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
763 glDisable(GL_TEXTURE_RECTANGLE_ARB);
764 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
766 glDisable(GL_TEXTURE_2D);
767 checkGLcall("glDisable GL_TEXTURE_2D");
769 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
770 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
772 if (sampler != -1) {
773 if (sampler < MAX_TEXTURES) {
774 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
776 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
779 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
780 checkGLcall("glActiveTextureARB");
783 sampler = This->rev_tex_unit_map[0];
785 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
786 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
787 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
789 glDisable(GL_TEXTURE_3D);
790 checkGLcall("glDisable GL_TEXTURE_3D");
791 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
792 glDisable(GL_TEXTURE_RECTANGLE_ARB);
793 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
795 glDisable(GL_TEXTURE_2D);
796 checkGLcall("glDisable GL_TEXTURE_2D");
798 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
800 glMatrixMode(GL_TEXTURE);
801 checkGLcall("glMatrixMode(GL_TEXTURE)");
802 glLoadIdentity();
803 checkGLcall("glLoadIdentity()");
805 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
806 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
807 GL_TEXTURE_LOD_BIAS_EXT,
808 0.0);
809 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
812 if (sampler != -1) {
813 if (sampler < MAX_TEXTURES) {
814 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
815 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
817 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
820 /* Other misc states */
821 glDisable(GL_ALPHA_TEST);
822 checkGLcall("glDisable(GL_ALPHA_TEST)");
823 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
824 glDisable(GL_LIGHTING);
825 checkGLcall("glDisable GL_LIGHTING");
826 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
827 glDisable(GL_DEPTH_TEST);
828 checkGLcall("glDisable GL_DEPTH_TEST");
829 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
830 glDisable(GL_FOG);
831 checkGLcall("glDisable GL_FOG");
832 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
833 glDisable(GL_BLEND);
834 checkGLcall("glDisable GL_BLEND");
835 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
836 glDisable(GL_CULL_FACE);
837 checkGLcall("glDisable GL_CULL_FACE");
838 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
839 glDisable(GL_STENCIL_TEST);
840 checkGLcall("glDisable GL_STENCIL_TEST");
841 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
842 glDisable(GL_SCISSOR_TEST);
843 checkGLcall("glDisable GL_SCISSOR_TEST");
844 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
845 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
846 glDisable(GL_POINT_SPRITE_ARB);
847 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
848 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
850 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
851 checkGLcall("glColorMask");
852 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
853 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
854 glDisable(GL_COLOR_SUM_EXT);
855 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
856 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
858 if (GL_SUPPORT(NV_REGISTER_COMBINERS)) {
859 GL_EXTCALL(glFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB));
860 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
861 checkGLcall("glFinalCombinerInputNV");
864 /* Setup transforms */
865 glMatrixMode(GL_MODELVIEW);
866 checkGLcall("glMatrixMode(GL_MODELVIEW)");
867 glLoadIdentity();
868 checkGLcall("glLoadIdentity()");
869 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
871 context->last_was_rhw = TRUE;
872 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
874 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
875 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
876 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
877 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
878 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
879 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
880 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
882 set_blit_dimension(width, height);
883 context->blit_w = width; context->blit_h = height;
884 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
885 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
888 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
891 /*****************************************************************************
892 * findThreadContextForSwapChain
894 * Searches a swapchain for all contexts and picks one for the thread tid.
895 * If none can be found the swapchain is requested to create a new context
897 *****************************************************************************/
898 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
899 int i;
901 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
902 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
903 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
908 /* Create a new context for the thread */
909 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
912 /*****************************************************************************
913 * FindContext
915 * Finds a context for the current render target and thread
917 * Parameters:
918 * target: Render target to find the context for
919 * tid: Thread to activate the context for
921 * Returns: The needed context
923 *****************************************************************************/
924 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
925 IWineD3DSwapChain *swapchain = NULL;
926 HRESULT hr;
927 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
928 WineD3DContext *context = This->activeContext;
929 BOOL oldRenderOffscreen = This->render_offscreen;
930 const WINED3DFORMAT oldFmt = ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->resource.format;
931 const WINED3DFORMAT newFmt = ((IWineD3DSurfaceImpl *) target)->resource.format;
932 const struct StateEntry *StateTable = This->StateTable;
934 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
935 * the alpha blend state changes with different render target formats
937 if(oldFmt != newFmt) {
938 const GlPixelFormatDesc *glDesc;
939 const StaticPixelFormatDesc *old = getFormatDescEntry(oldFmt, NULL, NULL);
940 const StaticPixelFormatDesc *new = getFormatDescEntry(newFmt, &GLINFO_LOCATION, &glDesc);
942 /* Disable blending when the alphaMask has changed and when a format doesn't support blending */
943 if((old->alphaMask && !new->alphaMask) || (!old->alphaMask && new->alphaMask) || !(glDesc->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING)) {
944 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
948 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
949 if(hr == WINED3D_OK && swapchain) {
950 TRACE("Rendering onscreen\n");
952 context = findThreadContextForSwapChain(swapchain, tid);
954 This->render_offscreen = FALSE;
955 /* The context != This->activeContext will catch a NOP context change. This can occur
956 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
957 * rendering. No context change is needed in that case
960 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
961 if(This->pbufferContext && tid == This->pbufferContext->tid) {
962 This->pbufferContext->tid = 0;
965 IWineD3DSwapChain_Release(swapchain);
967 if(oldRenderOffscreen) {
968 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
969 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
970 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
971 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
972 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
975 } else {
976 TRACE("Rendering offscreen\n");
977 This->render_offscreen = TRUE;
979 switch(wined3d_settings.offscreen_rendering_mode) {
980 case ORM_FBO:
981 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
982 if(This->activeContext && tid == This->lastThread) {
983 context = This->activeContext;
984 } else {
985 /* This may happen if the app jumps straight into offscreen rendering
986 * Start using the context of the primary swapchain. tid == 0 is no problem
987 * for findThreadContextForSwapChain.
989 * Can also happen on thread switches - in that case findThreadContextForSwapChain
990 * is perfect to call.
992 context = findThreadContextForSwapChain(This->swapchains[0], tid);
994 break;
996 case ORM_PBUFFER:
998 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
999 if(This->pbufferContext == NULL ||
1000 This->pbufferWidth < targetimpl->currentDesc.Width ||
1001 This->pbufferHeight < targetimpl->currentDesc.Height) {
1002 if(This->pbufferContext) {
1003 DestroyContext(This, This->pbufferContext);
1006 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1007 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1009 This->pbufferContext = CreateContext(This, targetimpl,
1010 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1011 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1012 This->pbufferWidth = targetimpl->currentDesc.Width;
1013 This->pbufferHeight = targetimpl->currentDesc.Height;
1016 if(This->pbufferContext) {
1017 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1018 FIXME("The PBuffr context is only supported for one thread for now!\n");
1020 This->pbufferContext->tid = tid;
1021 context = This->pbufferContext;
1022 break;
1023 } else {
1024 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1025 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1029 case ORM_BACKBUFFER:
1030 /* Stay with the currently active context for back buffer rendering */
1031 if(This->activeContext && tid == This->lastThread) {
1032 context = This->activeContext;
1033 } else {
1034 /* This may happen if the app jumps straight into offscreen rendering
1035 * Start using the context of the primary swapchain. tid == 0 is no problem
1036 * for findThreadContextForSwapChain.
1038 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1039 * is perfect to call.
1041 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1043 break;
1046 if(!oldRenderOffscreen) {
1047 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1048 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1049 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1050 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1051 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1055 /* When switching away from an offscreen render target, and we're not using FBOs,
1056 * we have to read the drawable into the texture. This is done via PreLoad(and
1057 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1058 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1059 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1060 * is read. This leads to these possible situations:
1062 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1063 * Nothing to do, we don't even reach this code in this case...
1065 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1066 * The currently active context is OK for readback. Call PreLoad, and it
1067 * performs the read
1069 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1070 * Nothing to do - the drawable is unchanged
1072 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1073 * This is tricky. We have to get a context with the old drawable from somewhere
1074 * before we can switch to the new context. In this case, PreLoad calls
1075 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1076 * is case (2) then. The old drawable is activated for the new thread, and the
1077 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1078 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1079 * target for the new thread
1081 if (readTexture && This->lastActiveRenderTarget != target) {
1082 BOOL oldInDraw = This->isInDraw;
1084 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1085 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1086 * when using offscreen rendering with multithreading
1088 This->isInDraw = TRUE;
1090 /* Do that before switching the context:
1091 * Read the back buffer of the old drawable into the destination texture
1093 IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
1095 /* Assume that the drawable will be modified by some other things now */
1096 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1098 This->isInDraw = oldInDraw;
1101 return context;
1104 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1106 HRESULT hr;
1107 IWineD3DSwapChain *swapchain;
1109 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain);
1110 if (SUCCEEDED(hr))
1112 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1113 glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1114 checkGLcall("glDrawBuffers()");
1116 else
1118 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1120 if (!blit)
1122 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1124 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1125 checkGLcall("glDrawBuffers()");
1127 else
1129 glDrawBuffer(This->draw_buffers[0]);
1130 checkGLcall("glDrawBuffer()");
1132 } else {
1133 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1134 checkGLcall("glDrawBuffer()");
1137 else
1139 glDrawBuffer(This->offscreenBuffer);
1140 checkGLcall("glDrawBuffer()");
1145 /*****************************************************************************
1146 * ActivateContext
1148 * Finds a rendering context and drawable matching the device and render
1149 * target for the current thread, activates them and puts them into the
1150 * requested state.
1152 * Params:
1153 * This: Device to activate the context for
1154 * target: Requested render target
1155 * usage: Prepares the context for blitting, drawing or other actions
1157 *****************************************************************************/
1158 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1159 DWORD tid = GetCurrentThreadId();
1160 int i;
1161 DWORD dirtyState, idx;
1162 BYTE shift;
1163 WineD3DContext *context;
1164 const struct StateEntry *StateTable = This->StateTable;
1166 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1167 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1168 context = FindContext(This, target, tid);
1169 context->draw_buffer_dirty = TRUE;
1170 This->lastActiveRenderTarget = target;
1171 This->lastThread = tid;
1172 } else {
1173 /* Stick to the old context */
1174 context = This->activeContext;
1177 /* Activate the opengl context */
1178 if(last_device != This || context != This->activeContext) {
1179 BOOL ret;
1181 /* Prevent an unneeded context switch as those are expensive */
1182 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1183 TRACE("Already using gl context %p\n", context->glCtx);
1185 else {
1186 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1188 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1189 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1190 if(ret == FALSE) {
1191 ERR("Failed to activate the new context\n");
1192 } else if(!context->last_was_blit) {
1193 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1196 if(This->activeContext->vshader_const_dirty) {
1197 memset(This->activeContext->vshader_const_dirty, 1,
1198 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1200 if(This->activeContext->pshader_const_dirty) {
1201 memset(This->activeContext->pshader_const_dirty, 1,
1202 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1204 This->activeContext = context;
1205 last_device = This;
1208 /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
1209 ENTER_GL();
1211 switch (usage) {
1212 case CTXUSAGE_CLEAR:
1213 case CTXUSAGE_DRAWPRIM:
1214 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1215 apply_fbo_state((IWineD3DDevice *)This);
1217 if (context->draw_buffer_dirty) {
1218 apply_draw_buffer(This, target, FALSE);
1219 context->draw_buffer_dirty = FALSE;
1221 break;
1223 case CTXUSAGE_BLIT:
1224 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1225 if (This->render_offscreen) {
1226 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1227 bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1228 attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1229 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0));
1230 checkGLcall("glFramebufferRenderbufferEXT");
1231 } else {
1232 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1233 checkGLcall("glFramebufferRenderbufferEXT");
1235 context->draw_buffer_dirty = TRUE;
1237 if (context->draw_buffer_dirty) {
1238 apply_draw_buffer(This, target, TRUE);
1239 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1240 context->draw_buffer_dirty = FALSE;
1243 break;
1245 default:
1246 break;
1249 switch(usage) {
1250 case CTXUSAGE_RESOURCELOAD:
1251 /* This does not require any special states to be set up */
1252 break;
1254 case CTXUSAGE_CLEAR:
1255 if(context->last_was_blit) {
1256 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1259 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1260 * blending when clearing improves the clearing performance incredibly.
1262 glDisable(GL_BLEND);
1263 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1265 glEnable(GL_SCISSOR_TEST);
1266 checkGLcall("glEnable GL_SCISSOR_TEST");
1267 context->last_was_blit = FALSE;
1268 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1269 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1270 break;
1272 case CTXUSAGE_DRAWPRIM:
1273 /* This needs all dirty states applied */
1274 if(context->last_was_blit) {
1275 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1278 IWineD3DDeviceImpl_FindTexUnitMap(This);
1280 for(i=0; i < context->numDirtyEntries; i++) {
1281 dirtyState = context->dirtyArray[i];
1282 idx = dirtyState >> 5;
1283 shift = dirtyState & 0x1f;
1284 context->isStateDirty[idx] &= ~(1 << shift);
1285 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1287 context->numDirtyEntries = 0; /* This makes the whole list clean */
1288 context->last_was_blit = FALSE;
1289 break;
1291 case CTXUSAGE_BLIT:
1292 SetupForBlit(This, context,
1293 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1294 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1295 break;
1297 default:
1298 FIXME("Unexpected context usage requested\n");
1300 LEAVE_GL();