2 * Context and render target management in wined3d
4 * Copyright 2007 Stefan Dösinger for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include "wined3d_private.h"
28 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
30 #define GLINFO_LOCATION This->adapter->gl_info
32 /*****************************************************************************
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
40 * context: Context to mark the state dirty in
41 * state: State to mark dirty
43 *****************************************************************************/
44 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state) {
45 DWORD rep = StateTable[state].representative;
49 if(!rep || isStateDirty(context, rep)) return;
51 context->dirtyArray[context->numDirtyEntries++] = rep;
54 context->isStateDirty[idx] |= (1 << shift);
57 /*****************************************************************************
60 * Adds a context to the context array. Helper function for CreateContext
62 * This method is not called in performance-critical code paths, only when a
63 * new render target or swapchain is created. Thus performance is not an issue
67 * This: Device to add the context for
69 * glCtx: WGL context to add
70 * pbuffer: optional pbuffer used with this context
72 *****************************************************************************/
73 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
74 WineD3DContext **oldArray = This->contexts;
77 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
78 if(This->contexts == NULL) {
79 ERR("Unable to grow the context array\n");
80 This->contexts = oldArray;
84 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
87 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
88 if(This->contexts[This->numContexts] == NULL) {
89 ERR("Unable to allocate a new context\n");
90 HeapFree(GetProcessHeap(), 0, This->contexts);
91 This->contexts = oldArray;
95 This->contexts[This->numContexts]->hdc = hdc;
96 This->contexts[This->numContexts]->glCtx = glCtx;
97 This->contexts[This->numContexts]->pbuffer = pbuffer;
98 This->contexts[This->numContexts]->win_handle = win_handle;
99 HeapFree(GetProcessHeap(), 0, oldArray);
101 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
103 for(state = 0; state <= STATE_HIGHEST; state++) {
104 Context_MarkStateDirty(This->contexts[This->numContexts], state);
108 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
109 return This->contexts[This->numContexts - 1];
112 /*****************************************************************************
115 * Creates a new context for a window, or a pbuffer context.
118 * This: Device to activate the context for
119 * target: Surface this context will render to
120 * win_handle: handle to the window which we are drawing to
121 * create_pbuffer: tells whether to create a pbuffer or not
122 * pPresentParameters: contains the pixelformats to use for onscreen rendering
124 *****************************************************************************/
125 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
126 HDC oldDrawable, hdc;
127 HPBUFFERARB pbuffer = NULL;
128 HGLRC ctx = NULL, oldCtx;
129 WineD3DContext *ret = NULL;
132 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
134 #define PUSH1(att) attribs[nAttribs++] = (att);
135 #define PUSH2(att,value) attribs[nAttribs++] = (att); attribs[nAttribs++] = (value);
137 HDC hdc_parent = GetDC(win_handle);
138 int iPixelFormat = 0;
139 short redBits, greenBits, blueBits, alphaBits, colorBits;
140 short depthBits, stencilBits;
142 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
143 WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
147 unsigned int nFormats;
149 /* Retrieve the specifications for the pixelformat from the backbuffer / stencilbuffer */
150 getColorBits(target->resource.format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits);
151 getDepthStencilBits(StencilBufferFormat, &depthBits, &stencilBits);
152 PUSH2(WGL_DRAW_TO_PBUFFER_ARB, 1); /* We need pbuffer support; doublebuffering isn't needed */
153 PUSH2(WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB); /* Make sure we don't get a float or color index format */
154 PUSH2(WGL_COLOR_BITS_ARB, colorBits);
155 PUSH2(WGL_RED_BITS_ARB, redBits);
156 PUSH2(WGL_GREEN_BITS_ARB, greenBits);
157 PUSH2(WGL_BLUE_BITS_ARB, blueBits);
158 PUSH2(WGL_ALPHA_BITS_ARB, alphaBits);
159 PUSH2(WGL_DEPTH_BITS_ARB, depthBits);
160 PUSH2(WGL_STENCIL_BITS_ARB, stencilBits);
161 PUSH1(0); /* end the list */
163 /* Try to find a pixelformat that matches exactly. If that fails let ChoosePixelFormat try to find a close match */
164 if(!GL_EXTCALL(wglChoosePixelFormatARB(hdc_parent, (const int*)&attribs, NULL, 1, &iPixelFormat, &nFormats)))
166 PIXELFORMATDESCRIPTOR pfd;
168 TRACE("Falling back to ChoosePixelFormat as wglChoosePixelFormatARB failed\n");
170 ZeroMemory(&pfd, sizeof(pfd));
171 pfd.nSize = sizeof(pfd);
173 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER_DONTCARE | PFD_DRAW_TO_WINDOW;
174 pfd.iPixelType = PFD_TYPE_RGBA;
175 pfd.cColorBits = colorBits;
176 pfd.cDepthBits = depthBits;
177 pfd.cStencilBits = stencilBits;
178 pfd.iLayerType = PFD_MAIN_PLANE;
180 iPixelFormat = ChoosePixelFormat(hdc_parent, &pfd);
182 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
183 ERR("Can't find a suitable iPixelFormat for the pbuffer\n");
187 TRACE("Creating a pBuffer drawable for the new context\n");
188 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
190 ERR("Cannot create a pbuffer\n");
191 ReleaseDC(win_handle, hdc_parent);
195 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
196 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
198 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
199 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
200 ReleaseDC(win_handle, hdc_parent);
203 ReleaseDC(win_handle, hdc_parent);
205 PIXELFORMATDESCRIPTOR pfd;
207 short redBits, greenBits, blueBits, alphaBits, colorBits;
208 short depthBits=0, stencilBits=0;
212 unsigned int nFormats;
213 WINED3DFORMAT fmt = target->resource.format;
215 hdc = GetDC(win_handle);
217 ERR("Cannot retrieve a device context!\n");
221 /* PixelFormat selection */
222 PUSH2(WGL_DRAW_TO_WINDOW_ARB, GL_TRUE); /* We want to draw to a window */
223 PUSH2(WGL_DOUBLE_BUFFER_ARB, GL_TRUE);
224 PUSH2(WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB); /* Make sure we don't get a float or color index format */
225 PUSH2(WGL_SUPPORT_OPENGL_ARB, GL_TRUE);
226 PUSH2(WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB); /* Make sure we receive an accelerated format. On windows (at least on ATI) this is not always the case */
228 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
229 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
230 if(target->resource.format == WINED3DFMT_X4R4G4B4)
231 fmt = WINED3DFMT_A4R4G4B4;
232 else if(target->resource.format == WINED3DFMT_X8R8G8B8)
233 fmt = WINED3DFMT_A8R8G8B8;
235 /* We like to have two aux buffers in backbuffer mode */
236 PUSH2(WGL_AUX_BUFFERS_ARB, 2);
239 if(!getColorBits(fmt, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
240 ERR("Unable to get color bits for format %#x!\n", target->resource.format);
243 PUSH2(WGL_COLOR_BITS_ARB, colorBits);
244 PUSH2(WGL_RED_BITS_ARB, redBits);
245 PUSH2(WGL_GREEN_BITS_ARB, greenBits);
246 PUSH2(WGL_BLUE_BITS_ARB, blueBits);
247 PUSH2(WGL_ALPHA_BITS_ARB, alphaBits);
249 /* Retrieve the depth stencil format from the present parameters.
250 * The choice of the proper format can give a nice performance boost
251 * in case of GPU limited programs. */
252 if(pPresentParms->EnableAutoDepthStencil) {
253 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
254 if(!getDepthStencilBits(pPresentParms->AutoDepthStencilFormat, &depthBits, &stencilBits)) {
255 ERR("Unable to get depth / stencil bits for AutoDepthStencilFormat %#x!\n", pPresentParms->AutoDepthStencilFormat);
258 PUSH2(WGL_DEPTH_BITS_ARB, depthBits);
259 PUSH2(WGL_STENCIL_BITS_ARB, stencilBits);
262 PUSH1(0); /* end the list */
264 /* In case of failure hope that standard ChoosePixelFormat will find something suitable */
265 if(!GL_EXTCALL(wglChoosePixelFormatARB(hdc, (const int*)&attribs, NULL, 1, &iPixelFormat, &nFormats)))
267 /* PixelFormat selection */
268 ZeroMemory(&pfd, sizeof(pfd));
269 pfd.nSize = sizeof(pfd);
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);
281 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
282 ERR("Can't find a suitable iPixelFormat\n");
286 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
287 res = SetPixelFormat(hdc, iPixelFormat, NULL);
289 int oldPixelFormat = GetPixelFormat(hdc);
292 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
293 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
294 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
297 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
305 ctx = pwglCreateContext(hdc);
306 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
309 ERR("Failed to create a WGL context\n");
311 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
312 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
316 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
318 ERR("Failed to add the newly created context to the context list\n");
319 pwglDeleteContext(ctx);
321 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
322 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
326 ret->surface = (IWineD3DSurface *) target;
327 ret->isPBuffer = create_pbuffer;
328 ret->tid = GetCurrentThreadId();
330 TRACE("Successfully created new context %p\n", ret);
332 /* Set up the context defaults */
333 oldCtx = pwglGetCurrentContext();
334 oldDrawable = pwglGetCurrentDC();
335 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
336 ERR("Cannot activate context to set up defaults\n");
341 TRACE("Setting up the screen\n");
342 /* Clear the screen */
343 glClearColor(1.0, 0.0, 0.0, 0.0);
344 checkGLcall("glClearColor");
347 glClearStencil(0xffff);
349 checkGLcall("glClear");
351 glColor3f(1.0, 1.0, 1.0);
352 checkGLcall("glColor3f");
354 glEnable(GL_LIGHTING);
355 checkGLcall("glEnable");
357 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
358 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
360 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
361 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
363 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
364 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
366 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
367 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
368 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
369 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
371 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
372 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
373 * and textures in DIB sections(due to the memory protection).
375 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
376 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
378 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
379 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
380 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
381 * GL_VERTEX_BLEND_ARB isn't enabled too
383 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
384 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
386 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
387 glEnable(GL_TEXTURE_SHADER_NV);
388 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
390 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
391 * the previous texture where to source the offset from is always unit - 1.
393 for(s = 1; s < GL_LIMITS(textures); s++) {
394 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
395 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
396 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
399 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
400 for(s = 0; s < GL_LIMITS(textures); s++) {
401 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
402 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
403 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
408 if(oldDrawable && oldCtx) {
409 pwglMakeCurrent(oldDrawable, oldCtx);
416 /*****************************************************************************
417 * RemoveContextFromArray
419 * Removes a context from the context manager. The opengl context is not
420 * destroyed or unset. context is not a valid pointer after that call.
422 * Similar to the former call this isn't a performance critical function. A
423 * helper function for DestroyContext.
426 * This: Device to activate the context for
427 * context: Context to remove
429 *****************************************************************************/
430 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
432 WineD3DContext **oldArray = This->contexts;
434 TRACE("Removing ctx %p\n", context);
438 if(This->numContexts) {
439 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
440 if(!This->contexts) {
441 ERR("Cannot allocate a new context array, PANIC!!!\n");
444 for(s = 0; s < This->numContexts; s++) {
445 if(oldArray[s] == context) continue;
446 This->contexts[t] = oldArray[s];
450 This->contexts = NULL;
453 HeapFree(GetProcessHeap(), 0, context);
454 HeapFree(GetProcessHeap(), 0, oldArray);
457 /*****************************************************************************
460 * Destroys a wineD3DContext
463 * This: Device to activate the context for
464 * context: Context to destroy
466 *****************************************************************************/
467 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
469 /* check that we are the current context first */
470 TRACE("Destroying ctx %p\n", context);
471 if(pwglGetCurrentContext() == context->glCtx){
472 pwglMakeCurrent(NULL, NULL);
475 if(context->isPBuffer) {
476 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
477 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
478 } else ReleaseDC(context->win_handle, context->hdc);
479 pwglDeleteContext(context->glCtx);
481 RemoveContextFromArray(This, context);
484 /*****************************************************************************
487 * Sets up a context for DirectDraw blitting.
488 * All texture units are disabled, texture unit 0 is set as current unit
489 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
490 * color writing enabled for all channels
491 * register combiners disabled, shaders disabled
492 * world matrix is set to identity, texture matrix 0 too
493 * projection matrix is setup for drawing screen coordinates
496 * This: Device to activate the context for
497 * context: Context to setup
498 * width: render target width
499 * height: render target height
501 *****************************************************************************/
502 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
505 TRACE("Setting up context %p for blitting\n", context);
506 if(context->last_was_blit) {
507 TRACE("Context is already set up for blitting, nothing to do\n");
510 context->last_was_blit = TRUE;
512 /* TODO: Use a display list */
514 /* Disable shaders */
515 This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
516 Context_MarkStateDirty(context, STATE_VSHADER);
517 Context_MarkStateDirty(context, STATE_PIXELSHADER);
519 /* Disable all textures. The caller can then bind a texture it wants to blit
522 if(GL_SUPPORT(NV_REGISTER_COMBINERS)) {
523 glDisable(GL_REGISTER_COMBINERS_NV);
524 checkGLcall("glDisable(GL_REGISTER_COMBINERS_NV)");
526 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
527 /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
528 * function texture unit. No need to care for higher samplers
530 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
531 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
532 checkGLcall("glActiveTextureARB");
534 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
535 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
536 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
538 glDisable(GL_TEXTURE_3D);
539 checkGLcall("glDisable GL_TEXTURE_3D");
540 glDisable(GL_TEXTURE_2D);
541 checkGLcall("glDisable GL_TEXTURE_2D");
543 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
544 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
546 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
547 Context_MarkStateDirty(context, STATE_SAMPLER(i));
549 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
550 checkGLcall("glActiveTextureARB");
552 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
553 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
554 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
556 glDisable(GL_TEXTURE_3D);
557 checkGLcall("glDisable GL_TEXTURE_3D");
558 glDisable(GL_TEXTURE_2D);
559 checkGLcall("glDisable GL_TEXTURE_2D");
561 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
563 glMatrixMode(GL_TEXTURE);
564 checkGLcall("glMatrixMode(GL_TEXTURE)");
566 checkGLcall("glLoadIdentity()");
567 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0));
569 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
570 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
571 GL_TEXTURE_LOD_BIAS_EXT,
573 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
575 Context_MarkStateDirty(context, STATE_SAMPLER(0));
576 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP));
578 /* Other misc states */
579 glDisable(GL_ALPHA_TEST);
580 checkGLcall("glDisable(GL_ALPHA_TEST)");
581 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE));
582 glDisable(GL_LIGHTING);
583 checkGLcall("glDisable GL_LIGHTING");
584 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING));
585 glDisable(GL_DEPTH_TEST);
586 checkGLcall("glDisable GL_DEPTH_TEST");
587 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE));
589 checkGLcall("glDisable GL_FOG");
590 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE));
592 checkGLcall("glDisable GL_BLEND");
593 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE));
594 glDisable(GL_CULL_FACE);
595 checkGLcall("glDisable GL_CULL_FACE");
596 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE));
597 glDisable(GL_STENCIL_TEST);
598 checkGLcall("glDisable GL_STENCIL_TEST");
599 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE));
600 glDisable(GL_SCISSOR_TEST);
601 checkGLcall("glDisable GL_SCISSOR_TEST");
602 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
603 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
604 glDisable(GL_POINT_SPRITE_ARB);
605 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
606 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE));
608 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
609 checkGLcall("glColorMask");
610 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING));
611 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
612 glDisable(GL_COLOR_SUM_EXT);
613 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE));
614 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
616 if (GL_SUPPORT(NV_REGISTER_COMBINERS)) {
617 GL_EXTCALL(glFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB));
618 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE));
619 checkGLcall("glFinalCombinerInputNV");
622 /* Setup transforms */
623 glMatrixMode(GL_MODELVIEW);
624 checkGLcall("glMatrixMode(GL_MODELVIEW)");
626 checkGLcall("glLoadIdentity()");
627 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)));
629 glMatrixMode(GL_PROJECTION);
630 checkGLcall("glMatrixMode(GL_PROJECTION)");
632 checkGLcall("glLoadIdentity()");
633 glOrtho(0, width, height, 0, 0.0, -1.0);
634 checkGLcall("glOrtho");
635 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION));
637 context->last_was_rhw = TRUE;
638 Context_MarkStateDirty(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
640 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
641 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
642 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
643 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
644 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
645 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
646 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING));
648 glViewport(0, 0, width, height);
649 checkGLcall("glViewport");
650 Context_MarkStateDirty(context, STATE_VIEWPORT);
652 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
653 glDisable(GL_TEXTURE_SHADER_NV);
654 checkGLcall("glDisable(GL_TEXTURE_SHADER_NV)");
658 /*****************************************************************************
659 * findThreadContextForSwapChain
661 * Searches a swapchain for all contexts and picks one for the thread tid.
662 * If none can be found the swapchain is requested to create a new context
664 *****************************************************************************/
665 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
668 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
669 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
670 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
675 /* Create a new context for the thread */
676 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
679 /*****************************************************************************
682 * Finds a context for the current render target and thread
685 * target: Render target to find the context for
686 * tid: Thread to activate the context for
688 * Returns: The needed context
690 *****************************************************************************/
691 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid, GLint *buffer) {
692 IWineD3DSwapChain *swapchain = NULL;
694 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
695 WineD3DContext *context = This->activeContext;
696 BOOL oldRenderOffscreen = This->render_offscreen;
697 const WINED3DFORMAT oldFmt = ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->resource.format;
698 const WINED3DFORMAT newFmt = ((IWineD3DSurfaceImpl *) target)->resource.format;
700 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
701 * the alpha blend state changes with different render target formats
703 if(oldFmt != newFmt) {
704 const StaticPixelFormatDesc *old = getFormatDescEntry(oldFmt, NULL, NULL);
705 const StaticPixelFormatDesc *new = getFormatDescEntry(oldFmt, NULL, NULL);
707 if((old->alphaMask && !new->alphaMask) || (!old->alphaMask && new->alphaMask)) {
708 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE));
712 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
713 if(hr == WINED3D_OK && swapchain) {
714 TRACE("Rendering onscreen\n");
716 context = findThreadContextForSwapChain(swapchain, tid);
718 This->render_offscreen = FALSE;
719 /* The context != This->activeContext will catch a NOP context change. This can occur
720 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
721 * rendering. No context change is needed in that case
724 if(((IWineD3DSwapChainImpl *) swapchain)->frontBuffer == target) {
729 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
730 if(This->pbufferContext && tid == This->pbufferContext->tid) {
731 This->pbufferContext->tid = 0;
734 IWineD3DSwapChain_Release(swapchain);
736 if(oldRenderOffscreen) {
737 Context_MarkStateDirty(context, WINED3DTS_PROJECTION);
738 Context_MarkStateDirty(context, STATE_VDECL);
739 Context_MarkStateDirty(context, STATE_VIEWPORT);
740 Context_MarkStateDirty(context, STATE_SCISSORRECT);
741 Context_MarkStateDirty(context, STATE_FRONTFACE);
745 TRACE("Rendering offscreen\n");
746 This->render_offscreen = TRUE;
747 *buffer = This->offscreenBuffer;
749 switch(wined3d_settings.offscreen_rendering_mode) {
751 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
752 if(This->activeContext && tid == This->lastThread) {
753 context = This->activeContext;
755 /* This may happen if the app jumps straight into offscreen rendering
756 * Start using the context of the primary swapchain. tid == 0 is no problem
757 * for findThreadContextForSwapChain.
759 * Can also happen on thread switches - in that case findThreadContextForSwapChain
760 * is perfect to call.
762 context = findThreadContextForSwapChain(This->swapchains[0], tid);
768 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
769 if(This->pbufferContext == NULL ||
770 This->pbufferWidth < targetimpl->currentDesc.Width ||
771 This->pbufferHeight < targetimpl->currentDesc.Height) {
772 if(This->pbufferContext) {
773 DestroyContext(This, This->pbufferContext);
776 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
777 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
779 This->pbufferContext = CreateContext(This, targetimpl,
780 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
781 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
782 This->pbufferWidth = targetimpl->currentDesc.Width;
783 This->pbufferHeight = targetimpl->currentDesc.Height;
786 if(This->pbufferContext) {
787 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
788 FIXME("The PBuffr context is only supported for one thread for now!\n");
790 This->pbufferContext->tid = tid;
791 context = This->pbufferContext;
794 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
795 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
800 /* Stay with the currently active context for back buffer rendering */
801 if(This->activeContext && tid == This->lastThread) {
802 context = This->activeContext;
804 /* This may happen if the app jumps straight into offscreen rendering
805 * Start using the context of the primary swapchain. tid == 0 is no problem
806 * for findThreadContextForSwapChain.
808 * Can also happen on thread switches - in that case findThreadContextForSwapChain
809 * is perfect to call.
811 context = findThreadContextForSwapChain(This->swapchains[0], tid);
816 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
817 /* Make sure we have a OpenGL texture name so the PreLoad() used to read the buffer
818 * back when we are done won't mark us dirty.
820 IWineD3DSurface_PreLoad(target);
823 if(!oldRenderOffscreen) {
824 Context_MarkStateDirty(context, WINED3DTS_PROJECTION);
825 Context_MarkStateDirty(context, STATE_VDECL);
826 Context_MarkStateDirty(context, STATE_VIEWPORT);
827 Context_MarkStateDirty(context, STATE_SCISSORRECT);
828 Context_MarkStateDirty(context, STATE_FRONTFACE);
832 BOOL oldInDraw = This->isInDraw;
834 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
835 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
836 * when using offscreen rendering with multithreading
838 This->isInDraw = TRUE;
840 /* Do that before switching the context:
841 * Read the back buffer of the old drawable into the destination texture
843 IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
845 /* Assume that the drawable will be modified by some other things now */
846 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
848 This->isInDraw = oldInDraw;
851 if(oldRenderOffscreen != This->render_offscreen && This->depth_copy_state != WINED3D_DCS_NO_COPY) {
852 This->depth_copy_state = WINED3D_DCS_COPY;
857 /*****************************************************************************
860 * Finds a rendering context and drawable matching the device and render
861 * target for the current thread, activates them and puts them into the
865 * This: Device to activate the context for
866 * target: Requested render target
867 * usage: Prepares the context for blitting, drawing or other actions
869 *****************************************************************************/
870 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
871 DWORD tid = GetCurrentThreadId();
873 DWORD dirtyState, idx;
875 WineD3DContext *context;
878 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
879 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
880 context = FindContext(This, target, tid, &drawBuffer);
881 This->lastActiveRenderTarget = target;
882 This->lastThread = tid;
884 /* Stick to the old context */
885 context = This->activeContext;
888 /* Activate the opengl context */
889 if(context != This->activeContext) {
892 /* Prevent an unneeded context switch as those are expensive */
893 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
894 TRACE("Already using gl context %p\n", context->glCtx);
897 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
898 ret = pwglMakeCurrent(context->hdc, context->glCtx);
900 ERR("Failed to activate the new context\n");
903 This->activeContext = context;
906 /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
908 /* Select the right draw buffer. It is selected in FindContext. */
909 if(drawBuffer && context->last_draw_buffer != drawBuffer) {
910 TRACE("Drawing to buffer: %#x\n", drawBuffer);
911 context->last_draw_buffer = drawBuffer;
913 glDrawBuffer(drawBuffer);
914 checkGLcall("glDrawBuffer");
918 case CTXUSAGE_RESOURCELOAD:
919 /* This does not require any special states to be set up */
923 if(context->last_was_blit && GL_SUPPORT(NV_TEXTURE_SHADER2)) {
924 glEnable(GL_TEXTURE_SHADER_NV);
925 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
928 glEnable(GL_SCISSOR_TEST);
929 checkGLcall("glEnable GL_SCISSOR_TEST");
930 context->last_was_blit = FALSE;
931 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
932 Context_MarkStateDirty(context, STATE_SCISSORRECT);
935 case CTXUSAGE_DRAWPRIM:
936 /* This needs all dirty states applied */
937 if(context->last_was_blit && GL_SUPPORT(NV_TEXTURE_SHADER2)) {
938 glEnable(GL_TEXTURE_SHADER_NV);
939 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
942 IWineD3DDeviceImpl_FindTexUnitMap(This);
944 for(i=0; i < context->numDirtyEntries; i++) {
945 dirtyState = context->dirtyArray[i];
946 idx = dirtyState >> 5;
947 shift = dirtyState & 0x1f;
948 context->isStateDirty[idx] &= ~(1 << shift);
949 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
951 context->numDirtyEntries = 0; /* This makes the whole list clean */
952 context->last_was_blit = FALSE;
956 SetupForBlit(This, context,
957 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
958 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
962 FIXME("Unexpected context usage requested\n");