ddraw: Set the bitdepth on YUV formats.
[wine/wine64.git] / dlls / wined3d / context.c
blob68ec2a79d5884c305c2ab30de3294027773a768d
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 aux buffers - this is the most common cause
133 * for not finding a pixel format. Also some drivers(the open source ones)
134 * only offer 32 bit ARB pixel formats. First try without an exact alpha
135 * match, then try without an exact alpha and color match.
137 { TRUE, TRUE, TRUE },
138 { FALSE, TRUE, TRUE },
139 { TRUE, FALSE, TRUE },
140 { TRUE, FALSE, FALSE },
141 { FALSE, FALSE, TRUE },
142 { FALSE, FALSE, FALSE },
145 int i = 0;
146 int nCfgs = This->adapter->nCfgs;
147 WineD3D_PixelFormat *cfgs = This->adapter->cfgs;
149 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
150 debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat), auxBuffers, numSamples, pbuffer, findCompatible);
152 if(!getColorBits(ColorFormat, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
153 ERR("Unable to get color bits for format %s (%#x)!\n", debug_d3dformat(ColorFormat), ColorFormat);
154 return 0;
157 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
158 * You are able to add a depth + stencil surface at a later stage when you need it.
159 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
160 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
161 * context, need torecreate shaders, textures and other resources.
163 * The context manager already takes care of the state problem and for the other tasks code from Reset
164 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
165 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
166 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
167 * issue needs to be fixed. */
168 if(DepthStencilFormat != WINED3DFMT_D24S8)
169 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
171 DepthStencilFormat = WINED3DFMT_D24S8;
173 if(DepthStencilFormat) {
174 getDepthStencilBits(DepthStencilFormat, &depthBits, &stencilBits);
177 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])); matchtry++) {
178 for(i=0; i<nCfgs; i++) {
179 BOOL exactDepthMatch = TRUE;
180 cfgs = &This->adapter->cfgs[i];
182 /* For now only accept RGBA formats. Perhaps some day we will
183 * allow floating point formats for pbuffers. */
184 if(cfgs->iPixelType != WGL_TYPE_RGBA_ARB)
185 continue;
187 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
188 if(!pbuffer && !(cfgs->windowDrawable && cfgs->doubleBuffer))
189 continue;
191 /* We like to have aux buffers in backbuffer mode */
192 if(auxBuffers && !cfgs->auxBuffers && matches[matchtry].require_aux)
193 continue;
195 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
196 if(pbuffer && (!cfgs->pbufferDrawable || cfgs->doubleBuffer))
197 continue;
199 if(matches[matchtry].exact_color) {
200 if(cfgs->redSize != redBits)
201 continue;
202 if(cfgs->greenSize != greenBits)
203 continue;
204 if(cfgs->blueSize != blueBits)
205 continue;
206 } else {
207 if(cfgs->redSize < redBits)
208 continue;
209 if(cfgs->greenSize < greenBits)
210 continue;
211 if(cfgs->blueSize < blueBits)
212 continue;
214 if(matches[matchtry].exact_alpha) {
215 if(cfgs->alphaSize != alphaBits)
216 continue;
217 } else {
218 if(cfgs->alphaSize < alphaBits)
219 continue;
222 /* We try to locate a format which matches our requirements exactly. In case of
223 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
224 if(cfgs->depthSize < depthBits)
225 continue;
226 else if(cfgs->depthSize > depthBits)
227 exactDepthMatch = FALSE;
229 /* In all cases make sure the number of stencil bits matches our requirements
230 * even when we don't need stencil because it could affect performance EXCEPT
231 * on cards which don't offer depth formats without stencil like the i915 drivers
232 * on Linux. */
233 if(stencilBits != cfgs->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfgs->stencilSize))
234 continue;
236 /* Check multisampling support */
237 if(cfgs->numSamples != numSamples)
238 continue;
240 /* When we have passed all the checks then we have found a format which matches our
241 * requirements. Note that we only check for a limit number of capabilities right now,
242 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
243 * can still differ in things like multisampling, stereo, SRGB and other flags.
246 /* Exit the loop as we have found a format :) */
247 if(exactDepthMatch) {
248 iPixelFormat = cfgs->iPixelFormat;
249 break;
250 } else if(!iPixelFormat) {
251 /* In the end we might end up with a format which doesn't exactly match our depth
252 * requirements. Accept the first format we found because formats with higher iPixelFormat
253 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
254 iPixelFormat = cfgs->iPixelFormat;
259 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
260 if(!iPixelFormat && !findCompatible) {
261 ERR("Can't find a suitable iPixelFormat\n");
262 return FALSE;
263 } else if(!iPixelFormat) {
264 PIXELFORMATDESCRIPTOR pfd;
266 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
267 /* PixelFormat selection */
268 ZeroMemory(&pfd, sizeof(pfd));
269 pfd.nSize = sizeof(pfd);
270 pfd.nVersion = 1;
271 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
272 pfd.iPixelType = PFD_TYPE_RGBA;
273 pfd.cAlphaBits = alphaBits;
274 pfd.cColorBits = colorBits;
275 pfd.cDepthBits = depthBits;
276 pfd.cStencilBits = stencilBits;
277 pfd.iLayerType = PFD_MAIN_PLANE;
279 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
280 if(!iPixelFormat) {
281 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
282 ERR("Can't find a suitable iPixelFormat\n");
283 return FALSE;
287 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n", iPixelFormat, debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat));
288 return iPixelFormat;
291 /*****************************************************************************
292 * CreateContext
294 * Creates a new context for a window, or a pbuffer context.
296 * * Params:
297 * This: Device to activate the context for
298 * target: Surface this context will render to
299 * win_handle: handle to the window which we are drawing to
300 * create_pbuffer: tells whether to create a pbuffer or not
301 * pPresentParameters: contains the pixelformats to use for onscreen rendering
303 *****************************************************************************/
304 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
305 HDC oldDrawable, hdc;
306 HPBUFFERARB pbuffer = NULL;
307 HGLRC ctx = NULL, oldCtx;
308 WineD3DContext *ret = NULL;
309 int s;
311 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
313 if(create_pbuffer) {
314 HDC hdc_parent = GetDC(win_handle);
315 int iPixelFormat = 0;
317 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
318 WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
320 /* Try to find a pixel format with pbuffer support. */
321 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */, FALSE /* findCompatible */);
322 if(!iPixelFormat) {
323 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
325 /* For some reason we weren't able to find a format, try to find something instead of crashing.
326 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
327 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */, TRUE /* findCompatible */);
330 /* This shouldn't happen as ChoosePixelFormat always returns something */
331 if(!iPixelFormat) {
332 ERR("Unable to locate a pixel format for a pbuffer\n");
333 ReleaseDC(win_handle, hdc_parent);
334 goto out;
337 TRACE("Creating a pBuffer drawable for the new context\n");
338 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
339 if(!pbuffer) {
340 ERR("Cannot create a pbuffer\n");
341 ReleaseDC(win_handle, hdc_parent);
342 goto out;
345 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
346 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
347 if(!hdc) {
348 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
349 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
350 ReleaseDC(win_handle, hdc_parent);
351 goto out;
353 ReleaseDC(win_handle, hdc_parent);
354 } else {
355 PIXELFORMATDESCRIPTOR pfd;
356 int iPixelFormat;
357 int res;
358 WINED3DFORMAT ColorFormat = target->resource.format;
359 WINED3DFORMAT DepthStencilFormat = 0;
360 BOOL auxBuffers = FALSE;
361 int numSamples = 0;
363 hdc = GetDC(win_handle);
364 if(hdc == NULL) {
365 ERR("Cannot retrieve a device context!\n");
366 goto out;
369 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
370 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
371 auxBuffers = TRUE;
373 if(target->resource.format == WINED3DFMT_X4R4G4B4)
374 ColorFormat = WINED3DFMT_A4R4G4B4;
375 else if(target->resource.format == WINED3DFMT_X8R8G8B8)
376 ColorFormat = WINED3DFMT_A8R8G8B8;
379 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
380 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
381 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
382 * a format with 8bit alpha, so request A8R8G8B8. */
383 if(ColorFormat == WINED3DFMT_P8)
384 ColorFormat = WINED3DFMT_A8R8G8B8;
386 /* Retrieve the depth stencil format from the present parameters.
387 * The choice of the proper format can give a nice performance boost
388 * in case of GPU limited programs. */
389 if(pPresentParms->EnableAutoDepthStencil) {
390 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
391 DepthStencilFormat = pPresentParms->AutoDepthStencilFormat;
394 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
395 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
396 if(!GL_SUPPORT(ARB_MULTISAMPLE))
397 ERR("The program is requesting multisampling without support!\n");
398 else {
399 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
400 numSamples = pPresentParms->MultiSampleType;
404 /* Try to find a pixel format which matches our requirements */
405 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
407 /* Try to locate a compatible format if we weren't able to find anything */
408 if(!iPixelFormat) {
409 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
410 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
413 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
414 if(!iPixelFormat) {
415 ERR("Can't find a suitable iPixelFormat\n");
416 return FALSE;
419 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
420 res = SetPixelFormat(hdc, iPixelFormat, NULL);
421 if(!res) {
422 int oldPixelFormat = GetPixelFormat(hdc);
424 /* By default WGL doesn't allow pixel format adjustments but we need it here.
425 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
426 * set the pixel format multiple times. Only use it when it is really needed. */
428 if(oldPixelFormat == iPixelFormat) {
429 /* We don't have to do anything as the formats are the same :) */
430 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
431 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
433 if(!res) {
434 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
435 return FALSE;
437 } else if(oldPixelFormat) {
438 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
439 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
440 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
441 } else {
442 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
443 return FALSE;
448 ctx = pwglCreateContext(hdc);
449 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
451 if(!ctx) {
452 ERR("Failed to create a WGL context\n");
453 if(create_pbuffer) {
454 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
455 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
457 goto out;
459 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
460 if(!ret) {
461 ERR("Failed to add the newly created context to the context list\n");
462 pwglDeleteContext(ctx);
463 if(create_pbuffer) {
464 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
465 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
467 goto out;
469 ret->surface = (IWineD3DSurface *) target;
470 ret->isPBuffer = create_pbuffer;
471 ret->tid = GetCurrentThreadId();
472 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
473 /* Create the dirty constants array and initialize them to dirty */
474 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
475 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
476 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
477 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
478 memset(ret->vshader_const_dirty, 1,
479 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
480 memset(ret->pshader_const_dirty, 1,
481 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
484 TRACE("Successfully created new context %p\n", ret);
486 /* Set up the context defaults */
487 oldCtx = pwglGetCurrentContext();
488 oldDrawable = pwglGetCurrentDC();
489 if(oldCtx && oldDrawable) {
490 /* See comment in ActivateContext context switching */
491 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
493 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
494 ERR("Cannot activate context to set up defaults\n");
495 goto out;
498 ENTER_GL();
500 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
502 TRACE("Setting up the screen\n");
503 /* Clear the screen */
504 glClearColor(1.0, 0.0, 0.0, 0.0);
505 checkGLcall("glClearColor");
506 glClearIndex(0);
507 glClearDepth(1);
508 glClearStencil(0xffff);
510 checkGLcall("glClear");
512 glColor3f(1.0, 1.0, 1.0);
513 checkGLcall("glColor3f");
515 glEnable(GL_LIGHTING);
516 checkGLcall("glEnable");
518 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
519 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
521 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
522 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
524 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
525 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
527 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
528 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
529 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
530 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
532 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
533 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
534 * and textures in DIB sections(due to the memory protection).
536 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
537 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
539 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
540 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
541 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
542 * GL_VERTEX_BLEND_ARB isn't enabled too
544 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
545 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
547 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
548 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
549 * the previous texture where to source the offset from is always unit - 1.
551 for(s = 1; s < GL_LIMITS(textures); s++) {
552 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
553 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
554 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
558 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
559 for(s = 0; s < GL_LIMITS(textures); s++) {
560 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
561 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
562 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
565 LEAVE_GL();
567 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
568 * but enable it for the first context we create, and reenable it on the old context
570 if(oldDrawable && oldCtx) {
571 pwglMakeCurrent(oldDrawable, oldCtx);
572 } else {
573 last_device = This;
575 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
577 out:
578 return ret;
581 /*****************************************************************************
582 * RemoveContextFromArray
584 * Removes a context from the context manager. The opengl context is not
585 * destroyed or unset. context is not a valid pointer after that call.
587 * Similar to the former call this isn't a performance critical function. A
588 * helper function for DestroyContext.
590 * Params:
591 * This: Device to activate the context for
592 * context: Context to remove
594 *****************************************************************************/
595 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
596 UINT t, s;
597 WineD3DContext **oldArray = This->contexts;
599 TRACE("Removing ctx %p\n", context);
601 This->numContexts--;
603 if(This->numContexts) {
604 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
605 if(!This->contexts) {
606 ERR("Cannot allocate a new context array, PANIC!!!\n");
608 t = 0;
609 /* Note that we decreased numContexts a few lines up, so use '<=' instead of '<' */
610 for(s = 0; s <= This->numContexts; s++) {
611 if(oldArray[s] == context) continue;
612 This->contexts[t] = oldArray[s];
613 t++;
615 } else {
616 This->contexts = NULL;
619 HeapFree(GetProcessHeap(), 0, context);
620 HeapFree(GetProcessHeap(), 0, oldArray);
623 /*****************************************************************************
624 * DestroyContext
626 * Destroys a wineD3DContext
628 * Params:
629 * This: Device to activate the context for
630 * context: Context to destroy
632 *****************************************************************************/
633 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
635 /* check that we are the current context first */
636 TRACE("Destroying ctx %p\n", context);
637 if(pwglGetCurrentContext() == context->glCtx){
638 pwglMakeCurrent(NULL, NULL);
639 } else {
640 last_device = NULL;
643 if(context->isPBuffer) {
644 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
645 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
646 } else ReleaseDC(context->win_handle, context->hdc);
647 pwglDeleteContext(context->glCtx);
649 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
650 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
651 RemoveContextFromArray(This, context);
654 static inline void set_blit_dimension(UINT width, UINT height) {
655 glMatrixMode(GL_PROJECTION);
656 checkGLcall("glMatrixMode(GL_PROJECTION)");
657 glLoadIdentity();
658 checkGLcall("glLoadIdentity()");
659 glOrtho(0, width, height, 0, 0.0, -1.0);
660 checkGLcall("glOrtho");
661 glViewport(0, 0, width, height);
662 checkGLcall("glViewport");
665 /*****************************************************************************
666 * SetupForBlit
668 * Sets up a context for DirectDraw blitting.
669 * All texture units are disabled, texture unit 0 is set as current unit
670 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
671 * color writing enabled for all channels
672 * register combiners disabled, shaders disabled
673 * world matrix is set to identity, texture matrix 0 too
674 * projection matrix is setup for drawing screen coordinates
676 * Params:
677 * This: Device to activate the context for
678 * context: Context to setup
679 * width: render target width
680 * height: render target height
682 *****************************************************************************/
683 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
684 int i, sampler;
685 const struct StateEntry *StateTable = This->StateTable;
687 TRACE("Setting up context %p for blitting\n", context);
688 if(context->last_was_blit) {
689 if(context->blit_w != width || context->blit_h != height) {
690 set_blit_dimension(width, height);
691 context->blit_w = width; context->blit_h = height;
692 /* No need to dirtify here, the states are still dirtified because they weren't
693 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
694 * be set
697 TRACE("Context is already set up for blitting, nothing to do\n");
698 return;
700 context->last_was_blit = TRUE;
702 /* TODO: Use a display list */
704 /* Disable shaders */
705 This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
706 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
707 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
709 /* Disable all textures. The caller can then bind a texture it wants to blit
710 * from
712 if(GL_SUPPORT(NV_REGISTER_COMBINERS)) {
713 glDisable(GL_REGISTER_COMBINERS_NV);
714 checkGLcall("glDisable(GL_REGISTER_COMBINERS_NV)");
716 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
717 /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
718 * function texture unit. No need to care for higher samplers
720 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
721 sampler = This->rev_tex_unit_map[i];
722 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
723 checkGLcall("glActiveTextureARB");
725 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
726 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
727 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
729 glDisable(GL_TEXTURE_3D);
730 checkGLcall("glDisable GL_TEXTURE_3D");
731 glDisable(GL_TEXTURE_2D);
732 checkGLcall("glDisable GL_TEXTURE_2D");
734 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
735 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
737 if (sampler != -1) {
738 if (sampler < MAX_TEXTURES) {
739 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
741 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
744 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
745 checkGLcall("glActiveTextureARB");
748 sampler = This->rev_tex_unit_map[0];
750 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
751 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
752 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
754 glDisable(GL_TEXTURE_3D);
755 checkGLcall("glDisable GL_TEXTURE_3D");
756 glDisable(GL_TEXTURE_2D);
757 checkGLcall("glDisable GL_TEXTURE_2D");
759 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
761 glMatrixMode(GL_TEXTURE);
762 checkGLcall("glMatrixMode(GL_TEXTURE)");
763 glLoadIdentity();
764 checkGLcall("glLoadIdentity()");
766 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
767 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
768 GL_TEXTURE_LOD_BIAS_EXT,
769 0.0);
770 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
773 if (sampler != -1) {
774 if (sampler < MAX_TEXTURES) {
775 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
776 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
778 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
781 /* Other misc states */
782 glDisable(GL_ALPHA_TEST);
783 checkGLcall("glDisable(GL_ALPHA_TEST)");
784 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
785 glDisable(GL_LIGHTING);
786 checkGLcall("glDisable GL_LIGHTING");
787 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
788 glDisable(GL_DEPTH_TEST);
789 checkGLcall("glDisable GL_DEPTH_TEST");
790 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
791 glDisable(GL_FOG);
792 checkGLcall("glDisable GL_FOG");
793 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
794 glDisable(GL_BLEND);
795 checkGLcall("glDisable GL_BLEND");
796 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
797 glDisable(GL_CULL_FACE);
798 checkGLcall("glDisable GL_CULL_FACE");
799 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
800 glDisable(GL_STENCIL_TEST);
801 checkGLcall("glDisable GL_STENCIL_TEST");
802 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
803 glDisable(GL_SCISSOR_TEST);
804 checkGLcall("glDisable GL_SCISSOR_TEST");
805 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
806 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
807 glDisable(GL_POINT_SPRITE_ARB);
808 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
809 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
811 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
812 checkGLcall("glColorMask");
813 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
814 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
815 glDisable(GL_COLOR_SUM_EXT);
816 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
817 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
819 if (GL_SUPPORT(NV_REGISTER_COMBINERS)) {
820 GL_EXTCALL(glFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB));
821 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
822 checkGLcall("glFinalCombinerInputNV");
825 /* Setup transforms */
826 glMatrixMode(GL_MODELVIEW);
827 checkGLcall("glMatrixMode(GL_MODELVIEW)");
828 glLoadIdentity();
829 checkGLcall("glLoadIdentity()");
830 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
832 context->last_was_rhw = TRUE;
833 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
835 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
836 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
837 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
838 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
839 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
840 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
841 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
843 set_blit_dimension(width, height);
844 context->blit_w = width; context->blit_h = height;
845 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
846 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
849 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
852 /*****************************************************************************
853 * findThreadContextForSwapChain
855 * Searches a swapchain for all contexts and picks one for the thread tid.
856 * If none can be found the swapchain is requested to create a new context
858 *****************************************************************************/
859 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
860 int i;
862 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
863 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
864 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
869 /* Create a new context for the thread */
870 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
873 /*****************************************************************************
874 * FindContext
876 * Finds a context for the current render target and thread
878 * Parameters:
879 * target: Render target to find the context for
880 * tid: Thread to activate the context for
882 * Returns: The needed context
884 *****************************************************************************/
885 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
886 IWineD3DSwapChain *swapchain = NULL;
887 HRESULT hr;
888 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
889 WineD3DContext *context = This->activeContext;
890 BOOL oldRenderOffscreen = This->render_offscreen;
891 const WINED3DFORMAT oldFmt = ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->resource.format;
892 const WINED3DFORMAT newFmt = ((IWineD3DSurfaceImpl *) target)->resource.format;
893 const struct StateEntry *StateTable = This->StateTable;
895 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
896 * the alpha blend state changes with different render target formats
898 if(oldFmt != newFmt) {
899 const GlPixelFormatDesc *glDesc;
900 const StaticPixelFormatDesc *old = getFormatDescEntry(oldFmt, NULL, NULL);
901 const StaticPixelFormatDesc *new = getFormatDescEntry(newFmt, &GLINFO_LOCATION, &glDesc);
903 /* Disable blending when the alphaMask has changed and when a format doesn't support blending */
904 if((old->alphaMask && !new->alphaMask) || (!old->alphaMask && new->alphaMask) || !(glDesc->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING)) {
905 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
909 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
910 if(hr == WINED3D_OK && swapchain) {
911 TRACE("Rendering onscreen\n");
913 context = findThreadContextForSwapChain(swapchain, tid);
915 This->render_offscreen = FALSE;
916 /* The context != This->activeContext will catch a NOP context change. This can occur
917 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
918 * rendering. No context change is needed in that case
921 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
922 if(This->pbufferContext && tid == This->pbufferContext->tid) {
923 This->pbufferContext->tid = 0;
926 IWineD3DSwapChain_Release(swapchain);
928 if(oldRenderOffscreen) {
929 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
930 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
931 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
932 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
933 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
936 } else {
937 TRACE("Rendering offscreen\n");
938 This->render_offscreen = TRUE;
940 switch(wined3d_settings.offscreen_rendering_mode) {
941 case ORM_FBO:
942 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
943 if(This->activeContext && tid == This->lastThread) {
944 context = This->activeContext;
945 } else {
946 /* This may happen if the app jumps straight into offscreen rendering
947 * Start using the context of the primary swapchain. tid == 0 is no problem
948 * for findThreadContextForSwapChain.
950 * Can also happen on thread switches - in that case findThreadContextForSwapChain
951 * is perfect to call.
953 context = findThreadContextForSwapChain(This->swapchains[0], tid);
955 break;
957 case ORM_PBUFFER:
959 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
960 if(This->pbufferContext == NULL ||
961 This->pbufferWidth < targetimpl->currentDesc.Width ||
962 This->pbufferHeight < targetimpl->currentDesc.Height) {
963 if(This->pbufferContext) {
964 DestroyContext(This, This->pbufferContext);
967 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
968 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
970 This->pbufferContext = CreateContext(This, targetimpl,
971 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
972 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
973 This->pbufferWidth = targetimpl->currentDesc.Width;
974 This->pbufferHeight = targetimpl->currentDesc.Height;
977 if(This->pbufferContext) {
978 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
979 FIXME("The PBuffr context is only supported for one thread for now!\n");
981 This->pbufferContext->tid = tid;
982 context = This->pbufferContext;
983 break;
984 } else {
985 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
986 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
990 case ORM_BACKBUFFER:
991 /* Stay with the currently active context for back buffer rendering */
992 if(This->activeContext && tid == This->lastThread) {
993 context = This->activeContext;
994 } else {
995 /* This may happen if the app jumps straight into offscreen rendering
996 * Start using the context of the primary swapchain. tid == 0 is no problem
997 * for findThreadContextForSwapChain.
999 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1000 * is perfect to call.
1002 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1004 break;
1007 if(!oldRenderOffscreen) {
1008 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1009 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1010 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1011 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1012 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1016 /* When switching away from an offscreen render target, and we're not using FBOs,
1017 * we have to read the drawable into the texture. This is done via PreLoad(and
1018 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1019 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1020 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1021 * is read. This leads to these possible situations:
1023 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1024 * Nothing to do, we don't even reach this code in this case...
1026 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1027 * The currently active context is OK for readback. Call PreLoad, and it
1028 * performs the read
1030 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1031 * Nothing to do - the drawable is unchanged
1033 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1034 * This is tricky. We have to get a context with the old drawable from somewhere
1035 * before we can switch to the new context. In this case, PreLoad calls
1036 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1037 * is case (2) then. The old drawable is activated for the new thread, and the
1038 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1039 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1040 * target for the new thread
1042 if (readTexture && This->lastActiveRenderTarget != target) {
1043 BOOL oldInDraw = This->isInDraw;
1045 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1046 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1047 * when using offscreen rendering with multithreading
1049 This->isInDraw = TRUE;
1051 /* Do that before switching the context:
1052 * Read the back buffer of the old drawable into the destination texture
1054 IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
1056 /* Assume that the drawable will be modified by some other things now */
1057 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1059 This->isInDraw = oldInDraw;
1062 return context;
1065 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1067 HRESULT hr;
1068 IWineD3DSwapChain *swapchain;
1070 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain);
1071 if (SUCCEEDED(hr))
1073 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1074 glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1075 checkGLcall("glDrawBuffers()");
1077 else
1079 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1081 if (!blit)
1083 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1085 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1086 checkGLcall("glDrawBuffers()");
1088 else
1090 glDrawBuffer(This->draw_buffers[0]);
1091 checkGLcall("glDrawBuffer()");
1093 } else {
1094 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1095 checkGLcall("glDrawBuffer()");
1098 else
1100 glDrawBuffer(This->offscreenBuffer);
1101 checkGLcall("glDrawBuffer()");
1106 /*****************************************************************************
1107 * ActivateContext
1109 * Finds a rendering context and drawable matching the device and render
1110 * target for the current thread, activates them and puts them into the
1111 * requested state.
1113 * Params:
1114 * This: Device to activate the context for
1115 * target: Requested render target
1116 * usage: Prepares the context for blitting, drawing or other actions
1118 *****************************************************************************/
1119 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1120 DWORD tid = GetCurrentThreadId();
1121 int i;
1122 DWORD dirtyState, idx;
1123 BYTE shift;
1124 WineD3DContext *context;
1125 const struct StateEntry *StateTable = This->StateTable;
1127 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1128 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1129 context = FindContext(This, target, tid);
1130 context->draw_buffer_dirty = TRUE;
1131 This->lastActiveRenderTarget = target;
1132 This->lastThread = tid;
1133 } else {
1134 /* Stick to the old context */
1135 context = This->activeContext;
1138 /* Activate the opengl context */
1139 if(last_device != This || context != This->activeContext) {
1140 BOOL ret;
1142 /* Prevent an unneeded context switch as those are expensive */
1143 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1144 TRACE("Already using gl context %p\n", context->glCtx);
1146 else {
1147 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1149 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1150 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1151 if(ret == FALSE) {
1152 ERR("Failed to activate the new context\n");
1153 } else if(!context->last_was_blit) {
1154 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1157 if(This->activeContext->vshader_const_dirty) {
1158 memset(This->activeContext->vshader_const_dirty, 1,
1159 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1161 if(This->activeContext->pshader_const_dirty) {
1162 memset(This->activeContext->pshader_const_dirty, 1,
1163 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1165 This->activeContext = context;
1166 last_device = This;
1169 /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
1170 ENTER_GL();
1172 switch (usage) {
1173 case CTXUSAGE_CLEAR:
1174 case CTXUSAGE_DRAWPRIM:
1175 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1176 apply_fbo_state((IWineD3DDevice *)This);
1178 if (context->draw_buffer_dirty) {
1179 apply_draw_buffer(This, target, FALSE);
1180 context->draw_buffer_dirty = FALSE;
1182 break;
1184 case CTXUSAGE_BLIT:
1185 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1186 if (This->render_offscreen) {
1187 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1188 bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &This->dst_fbo);
1189 attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1190 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0));
1191 checkGLcall("glFramebufferRenderbufferEXT");
1192 } else {
1193 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1194 checkGLcall("glFramebufferRenderbufferEXT");
1196 context->draw_buffer_dirty = TRUE;
1198 if (context->draw_buffer_dirty) {
1199 apply_draw_buffer(This, target, TRUE);
1200 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1201 context->draw_buffer_dirty = FALSE;
1204 break;
1206 default:
1207 break;
1210 switch(usage) {
1211 case CTXUSAGE_RESOURCELOAD:
1212 /* This does not require any special states to be set up */
1213 break;
1215 case CTXUSAGE_CLEAR:
1216 if(context->last_was_blit) {
1217 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1220 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1221 * blending when clearing improves the clearing performance incredibly.
1223 glDisable(GL_BLEND);
1224 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1226 glEnable(GL_SCISSOR_TEST);
1227 checkGLcall("glEnable GL_SCISSOR_TEST");
1228 context->last_was_blit = FALSE;
1229 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1230 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1231 break;
1233 case CTXUSAGE_DRAWPRIM:
1234 /* This needs all dirty states applied */
1235 if(context->last_was_blit) {
1236 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1239 IWineD3DDeviceImpl_FindTexUnitMap(This);
1241 for(i=0; i < context->numDirtyEntries; i++) {
1242 dirtyState = context->dirtyArray[i];
1243 idx = dirtyState >> 5;
1244 shift = dirtyState & 0x1f;
1245 context->isStateDirty[idx] &= ~(1 << shift);
1246 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1248 context->numDirtyEntries = 0; /* This makes the whole list clean */
1249 context->last_was_blit = FALSE;
1250 break;
1252 case CTXUSAGE_BLIT:
1253 SetupForBlit(This, context,
1254 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1255 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1256 break;
1258 default:
1259 FIXME("Unexpected context usage requested\n");
1261 LEAVE_GL();