push decde5eed3d79f9d889b4d757f73e86ce6ff9241
[wine/hacks.git] / dlls / wined3d / context.c
blobca81f3a5aca6b1b352e61304640d15f524bf2e6c
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 /*****************************************************************************
33 * Context_MarkStateDirty
35 * Marks a state in a context dirty. Only one context, opposed to
36 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
37 * contexts
39 * Params:
40 * context: Context to mark the state dirty in
41 * state: State to mark dirty
42 * StateTable: Pointer to the state table in use(for state grouping)
44 *****************************************************************************/
45 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
46 DWORD rep = StateTable[state].representative;
47 DWORD idx;
48 BYTE shift;
50 if(!rep || isStateDirty(context, rep)) return;
52 context->dirtyArray[context->numDirtyEntries++] = rep;
53 idx = rep >> 5;
54 shift = rep & 0x1f;
55 context->isStateDirty[idx] |= (1 << shift);
58 /*****************************************************************************
59 * AddContextToArray
61 * Adds a context to the context array. Helper function for CreateContext
63 * This method is not called in performance-critical code paths, only when a
64 * new render target or swapchain is created. Thus performance is not an issue
65 * here.
67 * Params:
68 * This: Device to add the context for
69 * hdc: device context
70 * glCtx: WGL context to add
71 * pbuffer: optional pbuffer used with this context
73 *****************************************************************************/
74 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
75 WineD3DContext **oldArray = This->contexts;
76 DWORD state;
78 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
79 if(This->contexts == NULL) {
80 ERR("Unable to grow the context array\n");
81 This->contexts = oldArray;
82 return NULL;
84 if(oldArray) {
85 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
88 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
89 if(This->contexts[This->numContexts] == NULL) {
90 ERR("Unable to allocate a new context\n");
91 HeapFree(GetProcessHeap(), 0, This->contexts);
92 This->contexts = oldArray;
93 return NULL;
96 This->contexts[This->numContexts]->hdc = hdc;
97 This->contexts[This->numContexts]->glCtx = glCtx;
98 This->contexts[This->numContexts]->pbuffer = pbuffer;
99 This->contexts[This->numContexts]->win_handle = win_handle;
100 HeapFree(GetProcessHeap(), 0, oldArray);
102 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
104 for(state = 0; state <= STATE_HIGHEST; state++) {
105 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
108 This->numContexts++;
109 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
110 return This->contexts[This->numContexts - 1];
113 /* This function takes care of WineD3D pixel format selection. */
114 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc, WINED3DFORMAT ColorFormat, WINED3DFORMAT DepthStencilFormat, BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
116 int iPixelFormat=0, matchtry;
117 short redBits, greenBits, blueBits, alphaBits, colorBits;
118 short depthBits=0, stencilBits=0;
120 struct match_type {
121 BOOL require_aux;
122 BOOL exact_alpha;
123 BOOL exact_color;
124 } matches[] = {
125 /* First, try without aux buffers - this is the most common cause
126 * for not finding a pixel format. Also some drivers(the open source ones)
127 * only offer 32 bit ARB pixel formats. First try without an exact alpha
128 * match, then try without an exact alpha and color match.
130 { TRUE, TRUE, TRUE },
131 { FALSE, TRUE, TRUE },
132 { TRUE, FALSE, TRUE },
133 { TRUE, FALSE, FALSE },
134 { FALSE, FALSE, TRUE },
135 { FALSE, FALSE, FALSE },
138 int i = 0;
139 int nCfgs = This->adapter->nCfgs;
140 WineD3D_PixelFormat *cfgs = This->adapter->cfgs;
142 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
143 debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat), auxBuffers, numSamples, pbuffer, findCompatible);
145 if(!getColorBits(ColorFormat, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
146 ERR("Unable to get color bits for format %s (%#x)!\n", debug_d3dformat(ColorFormat), ColorFormat);
147 return 0;
150 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
151 * You are able to add a depth + stencil surface at a later stage when you need it.
152 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
153 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
154 * context, need torecreate shaders, textures and other resources.
156 * The context manager already takes care of the state problem and for the other tasks code from Reset
157 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
158 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
159 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
160 * issue needs to be fixed. */
161 if(DepthStencilFormat != WINED3DFMT_D24S8)
162 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
164 DepthStencilFormat = WINED3DFMT_D24S8;
166 if(DepthStencilFormat) {
167 getDepthStencilBits(DepthStencilFormat, &depthBits, &stencilBits);
170 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])); matchtry++) {
171 for(i=0; i<nCfgs; i++) {
172 BOOL exactDepthMatch = TRUE;
173 cfgs = &This->adapter->cfgs[i];
175 /* For now only accept RGBA formats. Perhaps some day we will
176 * allow floating point formats for pbuffers. */
177 if(cfgs->iPixelType != WGL_TYPE_RGBA_ARB)
178 continue;
180 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
181 if(!pbuffer && !(cfgs->windowDrawable && cfgs->doubleBuffer))
182 continue;
184 /* We like to have aux buffers in backbuffer mode */
185 if(auxBuffers && !cfgs->auxBuffers && matches[matchtry].require_aux)
186 continue;
188 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
189 if(pbuffer && (!cfgs->pbufferDrawable || cfgs->doubleBuffer))
190 continue;
192 if(matches[matchtry].exact_color) {
193 if(cfgs->redSize != redBits)
194 continue;
195 if(cfgs->greenSize != greenBits)
196 continue;
197 if(cfgs->blueSize != blueBits)
198 continue;
199 } else {
200 if(cfgs->redSize < redBits)
201 continue;
202 if(cfgs->greenSize < greenBits)
203 continue;
204 if(cfgs->blueSize < blueBits)
205 continue;
207 if(matches[matchtry].exact_alpha) {
208 if(cfgs->alphaSize != alphaBits)
209 continue;
210 } else {
211 if(cfgs->alphaSize < alphaBits)
212 continue;
215 /* We try to locate a format which matches our requirements exactly. In case of
216 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
217 if(cfgs->depthSize < depthBits)
218 continue;
219 else if(cfgs->depthSize > depthBits)
220 exactDepthMatch = FALSE;
222 /* In all cases make sure the number of stencil bits matches our requirements
223 * even when we don't need stencil because it could affect performance EXCEPT
224 * on cards which don't offer depth formats without stencil like the i915 drivers
225 * on Linux. */
226 if(stencilBits != cfgs->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfgs->stencilSize))
227 continue;
229 /* Check multisampling support */
230 if(cfgs->numSamples != numSamples)
231 continue;
233 /* When we have passed all the checks then we have found a format which matches our
234 * requirements. Note that we only check for a limit number of capabilities right now,
235 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
236 * can still differ in things like multisampling, stereo, SRGB and other flags.
239 /* Exit the loop as we have found a format :) */
240 if(exactDepthMatch) {
241 iPixelFormat = cfgs->iPixelFormat;
242 break;
243 } else if(!iPixelFormat) {
244 /* In the end we might end up with a format which doesn't exactly match our depth
245 * requirements. Accept the first format we found because formats with higher iPixelFormat
246 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
247 iPixelFormat = cfgs->iPixelFormat;
252 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
253 if(!iPixelFormat && !findCompatible) {
254 ERR("Can't find a suitable iPixelFormat\n");
255 return FALSE;
256 } else if(!iPixelFormat) {
257 PIXELFORMATDESCRIPTOR pfd;
259 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
260 /* PixelFormat selection */
261 ZeroMemory(&pfd, sizeof(pfd));
262 pfd.nSize = sizeof(pfd);
263 pfd.nVersion = 1;
264 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
265 pfd.iPixelType = PFD_TYPE_RGBA;
266 pfd.cAlphaBits = alphaBits;
267 pfd.cColorBits = colorBits;
268 pfd.cDepthBits = depthBits;
269 pfd.cStencilBits = stencilBits;
270 pfd.iLayerType = PFD_MAIN_PLANE;
272 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
273 if(!iPixelFormat) {
274 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
275 ERR("Can't find a suitable iPixelFormat\n");
276 return FALSE;
280 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n", iPixelFormat, debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat));
281 return iPixelFormat;
284 /*****************************************************************************
285 * CreateContext
287 * Creates a new context for a window, or a pbuffer context.
289 * * Params:
290 * This: Device to activate the context for
291 * target: Surface this context will render to
292 * win_handle: handle to the window which we are drawing to
293 * create_pbuffer: tells whether to create a pbuffer or not
294 * pPresentParameters: contains the pixelformats to use for onscreen rendering
296 *****************************************************************************/
297 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
298 HDC oldDrawable, hdc;
299 HPBUFFERARB pbuffer = NULL;
300 HGLRC ctx = NULL, oldCtx;
301 WineD3DContext *ret = NULL;
302 int s;
304 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
306 if(create_pbuffer) {
307 HDC hdc_parent = GetDC(win_handle);
308 int iPixelFormat = 0;
310 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
311 WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
313 /* Try to find a pixel format with pbuffer support. */
314 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */, FALSE /* findCompatible */);
315 if(!iPixelFormat) {
316 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
318 /* For some reason we weren't able to find a format, try to find something instead of crashing.
319 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
320 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */, TRUE /* findCompatible */);
323 /* This shouldn't happen as ChoosePixelFormat always returns something */
324 if(!iPixelFormat) {
325 ERR("Unable to locate a pixel format for a pbuffer\n");
326 ReleaseDC(win_handle, hdc_parent);
327 goto out;
330 TRACE("Creating a pBuffer drawable for the new context\n");
331 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
332 if(!pbuffer) {
333 ERR("Cannot create a pbuffer\n");
334 ReleaseDC(win_handle, hdc_parent);
335 goto out;
338 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
339 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
340 if(!hdc) {
341 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
342 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
343 ReleaseDC(win_handle, hdc_parent);
344 goto out;
346 ReleaseDC(win_handle, hdc_parent);
347 } else {
348 PIXELFORMATDESCRIPTOR pfd;
349 int iPixelFormat;
350 int res;
351 WINED3DFORMAT ColorFormat = target->resource.format;
352 WINED3DFORMAT DepthStencilFormat = 0;
353 BOOL auxBuffers = FALSE;
354 int numSamples = 0;
356 hdc = GetDC(win_handle);
357 if(hdc == NULL) {
358 ERR("Cannot retrieve a device context!\n");
359 goto out;
362 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
363 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
364 auxBuffers = TRUE;
366 if(target->resource.format == WINED3DFMT_X4R4G4B4)
367 ColorFormat = WINED3DFMT_A4R4G4B4;
368 else if(target->resource.format == WINED3DFMT_X8R8G8B8)
369 ColorFormat = WINED3DFMT_A8R8G8B8;
372 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
373 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
374 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
375 * a format with 8bit alpha, so request A8R8G8B8. */
376 if(ColorFormat == WINED3DFMT_P8)
377 ColorFormat = WINED3DFMT_A8R8G8B8;
379 /* Retrieve the depth stencil format from the present parameters.
380 * The choice of the proper format can give a nice performance boost
381 * in case of GPU limited programs. */
382 if(pPresentParms->EnableAutoDepthStencil) {
383 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
384 DepthStencilFormat = pPresentParms->AutoDepthStencilFormat;
387 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
388 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
389 if(!GL_SUPPORT(ARB_MULTISAMPLE))
390 ERR("The program is requesting multisampling without support!\n");
391 else {
392 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
393 numSamples = pPresentParms->MultiSampleType;
397 /* Try to find a pixel format which matches our requirements */
398 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
400 /* Try to locate a compatible format if we weren't able to find anything */
401 if(!iPixelFormat) {
402 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
403 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
406 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
407 if(!iPixelFormat) {
408 ERR("Can't find a suitable iPixelFormat\n");
409 return FALSE;
412 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
413 res = SetPixelFormat(hdc, iPixelFormat, NULL);
414 if(!res) {
415 int oldPixelFormat = GetPixelFormat(hdc);
417 /* By default WGL doesn't allow pixel format adjustments but we need it here.
418 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
419 * set the pixel format multiple times. Only use it when it is really needed. */
421 if(oldPixelFormat == iPixelFormat) {
422 /* We don't have to do anything as the formats are the same :) */
423 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
424 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
426 if(!res) {
427 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
428 return FALSE;
430 } else if(oldPixelFormat) {
431 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
432 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
433 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
434 } else {
435 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
436 return FALSE;
441 ctx = pwglCreateContext(hdc);
442 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
444 if(!ctx) {
445 ERR("Failed to create a WGL context\n");
446 if(create_pbuffer) {
447 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
448 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
450 goto out;
452 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
453 if(!ret) {
454 ERR("Failed to add the newly created context to the context list\n");
455 pwglDeleteContext(ctx);
456 if(create_pbuffer) {
457 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
458 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
460 goto out;
462 ret->surface = (IWineD3DSurface *) target;
463 ret->isPBuffer = create_pbuffer;
464 ret->tid = GetCurrentThreadId();
465 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
466 /* Create the dirty constants array and initialize them to dirty */
467 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
468 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
469 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
470 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
471 memset(ret->vshader_const_dirty, 1,
472 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
473 memset(ret->pshader_const_dirty, 1,
474 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
477 TRACE("Successfully created new context %p\n", ret);
479 /* Set up the context defaults */
480 oldCtx = pwglGetCurrentContext();
481 oldDrawable = pwglGetCurrentDC();
482 if(oldCtx && oldDrawable) {
483 /* See comment in ActivateContext context switching */
484 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
486 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
487 ERR("Cannot activate context to set up defaults\n");
488 goto out;
491 ENTER_GL();
493 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
495 TRACE("Setting up the screen\n");
496 /* Clear the screen */
497 glClearColor(1.0, 0.0, 0.0, 0.0);
498 checkGLcall("glClearColor");
499 glClearIndex(0);
500 glClearDepth(1);
501 glClearStencil(0xffff);
503 checkGLcall("glClear");
505 glColor3f(1.0, 1.0, 1.0);
506 checkGLcall("glColor3f");
508 glEnable(GL_LIGHTING);
509 checkGLcall("glEnable");
511 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
512 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
514 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
515 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
517 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
518 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
520 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
521 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
522 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
523 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
525 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
526 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
527 * and textures in DIB sections(due to the memory protection).
529 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
530 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
532 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
533 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
534 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
535 * GL_VERTEX_BLEND_ARB isn't enabled too
537 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
538 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
540 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
541 glEnable(GL_TEXTURE_SHADER_NV);
542 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
544 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
545 * the previous texture where to source the offset from is always unit - 1.
547 for(s = 1; s < GL_LIMITS(textures); s++) {
548 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
549 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
550 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
554 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
555 for(s = 0; s < GL_LIMITS(textures); s++) {
556 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
557 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
558 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
561 LEAVE_GL();
563 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
564 * but enable it for the first context we create, and reenable it on the old context
566 if(oldDrawable && oldCtx) {
567 pwglMakeCurrent(oldDrawable, oldCtx);
569 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
571 out:
572 return ret;
575 /*****************************************************************************
576 * RemoveContextFromArray
578 * Removes a context from the context manager. The opengl context is not
579 * destroyed or unset. context is not a valid pointer after that call.
581 * Similar to the former call this isn't a performance critical function. A
582 * helper function for DestroyContext.
584 * Params:
585 * This: Device to activate the context for
586 * context: Context to remove
588 *****************************************************************************/
589 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
590 UINT t, s;
591 WineD3DContext **oldArray = This->contexts;
593 TRACE("Removing ctx %p\n", context);
595 This->numContexts--;
597 if(This->numContexts) {
598 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
599 if(!This->contexts) {
600 ERR("Cannot allocate a new context array, PANIC!!!\n");
602 t = 0;
603 /* Note that we decreased numContexts a few lines up, so use '<=' instead of '<' */
604 for(s = 0; s <= This->numContexts; s++) {
605 if(oldArray[s] == context) continue;
606 This->contexts[t] = oldArray[s];
607 t++;
609 } else {
610 This->contexts = NULL;
613 HeapFree(GetProcessHeap(), 0, context);
614 HeapFree(GetProcessHeap(), 0, oldArray);
617 /*****************************************************************************
618 * DestroyContext
620 * Destroys a wineD3DContext
622 * Params:
623 * This: Device to activate the context for
624 * context: Context to destroy
626 *****************************************************************************/
627 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
629 /* check that we are the current context first */
630 TRACE("Destroying ctx %p\n", context);
631 if(pwglGetCurrentContext() == context->glCtx){
632 pwglMakeCurrent(NULL, NULL);
635 if(context->isPBuffer) {
636 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
637 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
638 } else ReleaseDC(context->win_handle, context->hdc);
639 pwglDeleteContext(context->glCtx);
641 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
642 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
643 RemoveContextFromArray(This, context);
646 static inline void set_blit_dimension(UINT width, UINT height) {
647 glMatrixMode(GL_PROJECTION);
648 checkGLcall("glMatrixMode(GL_PROJECTION)");
649 glLoadIdentity();
650 checkGLcall("glLoadIdentity()");
651 glOrtho(0, width, height, 0, 0.0, -1.0);
652 checkGLcall("glOrtho");
653 glViewport(0, 0, width, height);
654 checkGLcall("glViewport");
657 /*****************************************************************************
658 * SetupForBlit
660 * Sets up a context for DirectDraw blitting.
661 * All texture units are disabled, texture unit 0 is set as current unit
662 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
663 * color writing enabled for all channels
664 * register combiners disabled, shaders disabled
665 * world matrix is set to identity, texture matrix 0 too
666 * projection matrix is setup for drawing screen coordinates
668 * Params:
669 * This: Device to activate the context for
670 * context: Context to setup
671 * width: render target width
672 * height: render target height
674 *****************************************************************************/
675 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
676 int i, sampler;
677 const struct StateEntry *StateTable = This->StateTable;
679 TRACE("Setting up context %p for blitting\n", context);
680 if(context->last_was_blit) {
681 if(context->blit_w != width || context->blit_h != height) {
682 set_blit_dimension(width, height);
683 context->blit_w = width; context->blit_h = height;
684 /* No need to dirtify here, the states are still dirtified because they weren't
685 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
686 * be set
689 TRACE("Context is already set up for blitting, nothing to do\n");
690 return;
692 context->last_was_blit = TRUE;
694 /* TODO: Use a display list */
696 /* Disable shaders */
697 This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
698 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
699 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
701 /* Disable all textures. The caller can then bind a texture it wants to blit
702 * from
704 if(GL_SUPPORT(NV_REGISTER_COMBINERS)) {
705 glDisable(GL_REGISTER_COMBINERS_NV);
706 checkGLcall("glDisable(GL_REGISTER_COMBINERS_NV)");
708 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
709 /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
710 * function texture unit. No need to care for higher samplers
712 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
713 sampler = This->rev_tex_unit_map[i];
714 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
715 checkGLcall("glActiveTextureARB");
717 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
718 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
719 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
721 glDisable(GL_TEXTURE_3D);
722 checkGLcall("glDisable GL_TEXTURE_3D");
723 glDisable(GL_TEXTURE_2D);
724 checkGLcall("glDisable GL_TEXTURE_2D");
726 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
727 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
729 if (sampler != -1) {
730 if (sampler < MAX_TEXTURES) {
731 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
733 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
736 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
737 checkGLcall("glActiveTextureARB");
740 sampler = This->rev_tex_unit_map[0];
742 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
743 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
744 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
746 glDisable(GL_TEXTURE_3D);
747 checkGLcall("glDisable GL_TEXTURE_3D");
748 glDisable(GL_TEXTURE_2D);
749 checkGLcall("glDisable GL_TEXTURE_2D");
751 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
753 glMatrixMode(GL_TEXTURE);
754 checkGLcall("glMatrixMode(GL_TEXTURE)");
755 glLoadIdentity();
756 checkGLcall("glLoadIdentity()");
758 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
759 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
760 GL_TEXTURE_LOD_BIAS_EXT,
761 0.0);
762 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
765 if (sampler != -1) {
766 if (sampler < MAX_TEXTURES) {
767 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
768 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
770 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
773 /* Other misc states */
774 glDisable(GL_ALPHA_TEST);
775 checkGLcall("glDisable(GL_ALPHA_TEST)");
776 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
777 glDisable(GL_LIGHTING);
778 checkGLcall("glDisable GL_LIGHTING");
779 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
780 glDisable(GL_DEPTH_TEST);
781 checkGLcall("glDisable GL_DEPTH_TEST");
782 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
783 glDisable(GL_FOG);
784 checkGLcall("glDisable GL_FOG");
785 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
786 glDisable(GL_BLEND);
787 checkGLcall("glDisable GL_BLEND");
788 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
789 glDisable(GL_CULL_FACE);
790 checkGLcall("glDisable GL_CULL_FACE");
791 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
792 glDisable(GL_STENCIL_TEST);
793 checkGLcall("glDisable GL_STENCIL_TEST");
794 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
795 glDisable(GL_SCISSOR_TEST);
796 checkGLcall("glDisable GL_SCISSOR_TEST");
797 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
798 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
799 glDisable(GL_POINT_SPRITE_ARB);
800 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
801 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
803 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
804 checkGLcall("glColorMask");
805 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
806 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
807 glDisable(GL_COLOR_SUM_EXT);
808 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
809 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
811 if (GL_SUPPORT(NV_REGISTER_COMBINERS)) {
812 GL_EXTCALL(glFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB));
813 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
814 checkGLcall("glFinalCombinerInputNV");
817 /* Setup transforms */
818 glMatrixMode(GL_MODELVIEW);
819 checkGLcall("glMatrixMode(GL_MODELVIEW)");
820 glLoadIdentity();
821 checkGLcall("glLoadIdentity()");
822 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
824 context->last_was_rhw = TRUE;
825 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
827 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
828 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
829 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
830 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
831 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
832 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
833 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
835 set_blit_dimension(width, height);
836 context->blit_w = width; context->blit_h = height;
837 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
838 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
841 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
844 /*****************************************************************************
845 * findThreadContextForSwapChain
847 * Searches a swapchain for all contexts and picks one for the thread tid.
848 * If none can be found the swapchain is requested to create a new context
850 *****************************************************************************/
851 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
852 int i;
854 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
855 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
856 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
861 /* Create a new context for the thread */
862 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
865 /*****************************************************************************
866 * FindContext
868 * Finds a context for the current render target and thread
870 * Parameters:
871 * target: Render target to find the context for
872 * tid: Thread to activate the context for
874 * Returns: The needed context
876 *****************************************************************************/
877 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid, GLint *buffer) {
878 IWineD3DSwapChain *swapchain = NULL;
879 HRESULT hr;
880 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
881 WineD3DContext *context = This->activeContext;
882 BOOL oldRenderOffscreen = This->render_offscreen;
883 const WINED3DFORMAT oldFmt = ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->resource.format;
884 const WINED3DFORMAT newFmt = ((IWineD3DSurfaceImpl *) target)->resource.format;
885 const struct StateEntry *StateTable = This->StateTable;
887 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
888 * the alpha blend state changes with different render target formats
890 if(oldFmt != newFmt) {
891 const GlPixelFormatDesc *glDesc;
892 const StaticPixelFormatDesc *old = getFormatDescEntry(oldFmt, NULL, NULL);
893 const StaticPixelFormatDesc *new = getFormatDescEntry(newFmt, &GLINFO_LOCATION, &glDesc);
895 /* Disable blending when the alphaMask has changed and when a format doesn't support blending */
896 if((old->alphaMask && !new->alphaMask) || (!old->alphaMask && new->alphaMask) || !(glDesc->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING)) {
897 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
901 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
902 if(hr == WINED3D_OK && swapchain) {
903 TRACE("Rendering onscreen\n");
905 context = findThreadContextForSwapChain(swapchain, tid);
907 This->render_offscreen = FALSE;
908 /* The context != This->activeContext will catch a NOP context change. This can occur
909 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
910 * rendering. No context change is needed in that case
913 if(((IWineD3DSwapChainImpl *) swapchain)->frontBuffer == target) {
914 *buffer = GL_FRONT;
915 } else {
916 *buffer = GL_BACK;
918 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
919 if(This->pbufferContext && tid == This->pbufferContext->tid) {
920 This->pbufferContext->tid = 0;
923 IWineD3DSwapChain_Release(swapchain);
925 if(oldRenderOffscreen) {
926 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
927 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
928 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
929 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
930 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
933 } else {
934 TRACE("Rendering offscreen\n");
935 This->render_offscreen = TRUE;
936 *buffer = This->offscreenBuffer;
938 switch(wined3d_settings.offscreen_rendering_mode) {
939 case ORM_FBO:
940 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
941 if(This->activeContext && tid == This->lastThread) {
942 context = This->activeContext;
943 } else {
944 /* This may happen if the app jumps straight into offscreen rendering
945 * Start using the context of the primary swapchain. tid == 0 is no problem
946 * for findThreadContextForSwapChain.
948 * Can also happen on thread switches - in that case findThreadContextForSwapChain
949 * is perfect to call.
951 context = findThreadContextForSwapChain(This->swapchains[0], tid);
953 break;
955 case ORM_PBUFFER:
957 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
958 if(This->pbufferContext == NULL ||
959 This->pbufferWidth < targetimpl->currentDesc.Width ||
960 This->pbufferHeight < targetimpl->currentDesc.Height) {
961 if(This->pbufferContext) {
962 DestroyContext(This, This->pbufferContext);
965 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
966 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
968 This->pbufferContext = CreateContext(This, targetimpl,
969 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
970 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
971 This->pbufferWidth = targetimpl->currentDesc.Width;
972 This->pbufferHeight = targetimpl->currentDesc.Height;
975 if(This->pbufferContext) {
976 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
977 FIXME("The PBuffr context is only supported for one thread for now!\n");
979 This->pbufferContext->tid = tid;
980 context = This->pbufferContext;
981 break;
982 } else {
983 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
984 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
988 case ORM_BACKBUFFER:
989 /* Stay with the currently active context for back buffer rendering */
990 if(This->activeContext && tid == This->lastThread) {
991 context = This->activeContext;
992 } else {
993 /* This may happen if the app jumps straight into offscreen rendering
994 * Start using the context of the primary swapchain. tid == 0 is no problem
995 * for findThreadContextForSwapChain.
997 * Can also happen on thread switches - in that case findThreadContextForSwapChain
998 * is perfect to call.
1000 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1002 break;
1005 if(!oldRenderOffscreen) {
1006 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1007 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1008 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1009 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1010 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1014 /* When switching away from an offscreen render target, and we're not using FBOs,
1015 * we have to read the drawable into the texture. This is done via PreLoad(and
1016 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1017 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1018 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1019 * is read. This leads to these possible situations:
1021 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1022 * Nothing to do, we don't even reach this code in this case...
1024 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1025 * The currently active context is OK for readback. Call PreLoad, and it
1026 * performs the read
1028 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1029 * Nothing to do - the drawable is unchanged
1031 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1032 * This is tricky. We have to get a context with the old drawable from somewhere
1033 * before we can switch to the new context. In this case, PreLoad calls
1034 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1035 * is case (2) then. The old drawable is activated for the new thread, and the
1036 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1037 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1038 * target for the new thread
1040 if (readTexture && This->lastActiveRenderTarget != target) {
1041 BOOL oldInDraw = This->isInDraw;
1043 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1044 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1045 * when using offscreen rendering with multithreading
1047 This->isInDraw = TRUE;
1049 /* Do that before switching the context:
1050 * Read the back buffer of the old drawable into the destination texture
1052 IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
1054 /* Assume that the drawable will be modified by some other things now */
1055 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1057 This->isInDraw = oldInDraw;
1060 return context;
1063 /*****************************************************************************
1064 * ActivateContext
1066 * Finds a rendering context and drawable matching the device and render
1067 * target for the current thread, activates them and puts them into the
1068 * requested state.
1070 * Params:
1071 * This: Device to activate the context for
1072 * target: Requested render target
1073 * usage: Prepares the context for blitting, drawing or other actions
1075 *****************************************************************************/
1076 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1077 DWORD tid = GetCurrentThreadId();
1078 int i;
1079 DWORD dirtyState, idx;
1080 BYTE shift;
1081 WineD3DContext *context;
1082 GLint drawBuffer=0;
1083 const struct StateEntry *StateTable = This->StateTable;
1085 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1086 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1087 context = FindContext(This, target, tid, &drawBuffer);
1088 This->lastActiveRenderTarget = target;
1089 This->lastThread = tid;
1090 } else {
1091 /* Stick to the old context */
1092 context = This->activeContext;
1095 /* Activate the opengl context */
1096 if(context != This->activeContext) {
1097 BOOL ret;
1099 /* Prevent an unneeded context switch as those are expensive */
1100 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1101 TRACE("Already using gl context %p\n", context->glCtx);
1103 else {
1104 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1106 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1107 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1108 if(ret == FALSE) {
1109 ERR("Failed to activate the new context\n");
1110 } else if(!context->last_was_blit) {
1111 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1114 if(This->activeContext->vshader_const_dirty) {
1115 memset(This->activeContext->vshader_const_dirty, 1,
1116 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1118 if(This->activeContext->pshader_const_dirty) {
1119 memset(This->activeContext->pshader_const_dirty, 1,
1120 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1122 This->activeContext = context;
1125 /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
1126 ENTER_GL();
1127 /* Select the right draw buffer. It is selected in FindContext. */
1128 if(drawBuffer && context->last_draw_buffer != drawBuffer) {
1129 TRACE("Drawing to buffer: %#x\n", drawBuffer);
1130 context->last_draw_buffer = drawBuffer;
1132 glDrawBuffer(drawBuffer);
1133 checkGLcall("glDrawBuffer");
1136 switch(usage) {
1137 case CTXUSAGE_RESOURCELOAD:
1138 /* This does not require any special states to be set up */
1139 break;
1141 case CTXUSAGE_CLEAR:
1142 if(context->last_was_blit) {
1143 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1146 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1147 * blending when clearing improves the clearing performance incredibly.
1149 glDisable(GL_BLEND);
1150 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1152 glEnable(GL_SCISSOR_TEST);
1153 checkGLcall("glEnable GL_SCISSOR_TEST");
1154 context->last_was_blit = FALSE;
1155 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1156 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1157 break;
1159 case CTXUSAGE_DRAWPRIM:
1160 /* This needs all dirty states applied */
1161 if(context->last_was_blit) {
1162 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1165 IWineD3DDeviceImpl_FindTexUnitMap(This);
1167 for(i=0; i < context->numDirtyEntries; i++) {
1168 dirtyState = context->dirtyArray[i];
1169 idx = dirtyState >> 5;
1170 shift = dirtyState & 0x1f;
1171 context->isStateDirty[idx] &= ~(1 << shift);
1172 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1174 context->numDirtyEntries = 0; /* This makes the whole list clean */
1175 context->last_was_blit = FALSE;
1176 break;
1178 case CTXUSAGE_BLIT:
1179 SetupForBlit(This, context,
1180 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1181 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1182 break;
1184 default:
1185 FIXME("Unexpected context usage requested\n");
1187 LEAVE_GL();