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;
214 hdc = GetDC(win_handle);
216 ERR("Cannot retrieve a device context!\n");
220 /* PixelFormat selection */
221 PUSH2(WGL_DRAW_TO_WINDOW_ARB, GL_TRUE); /* We want to draw to a window */
222 PUSH2(WGL_DOUBLE_BUFFER_ARB, GL_TRUE);
223 PUSH2(WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB); /* Make sure we don't get a float or color index format */
225 if(!getColorBits(target->resource.format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
226 ERR("Unable to get color bits for format %#x!\n", target->resource.format);
229 PUSH2(WGL_COLOR_BITS_ARB, colorBits);
230 PUSH2(WGL_RED_BITS_ARB, redBits);
231 PUSH2(WGL_GREEN_BITS_ARB, greenBits);
232 PUSH2(WGL_BLUE_BITS_ARB, blueBits);
233 PUSH2(WGL_ALPHA_BITS_ARB, alphaBits);
235 /* Retrieve the depth stencil format from the present parameters.
236 * The choice of the proper format can give a nice performance boost
237 * in case of GPU limited programs. */
238 if(pPresentParms->EnableAutoDepthStencil) {
239 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
240 if(!getDepthStencilBits(pPresentParms->AutoDepthStencilFormat, &depthBits, &stencilBits)) {
241 ERR("Unable to get depth / stencil bits for AutoDepthStencilFormat %#x!\n", pPresentParms->AutoDepthStencilFormat);
244 PUSH2(WGL_DEPTH_BITS_ARB, depthBits);
245 PUSH2(WGL_STENCIL_BITS_ARB, stencilBits);
248 PUSH1(0); /* end the list */
249 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
251 /* In case of failure hope that standard ChooosePixelFormat will find something suitable */
252 if(!GL_EXTCALL(wglChoosePixelFormatARB(hdc, (const int*)&attribs, NULL, 1, &iPixelFormat, &nFormats)))
254 /* PixelFormat selection */
255 ZeroMemory(&pfd, sizeof(pfd));
256 pfd.nSize = sizeof(pfd);
258 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
259 pfd.iPixelType = PFD_TYPE_RGBA;
260 pfd.cAlphaBits = alphaBits;
261 pfd.cColorBits = colorBits;
262 pfd.cDepthBits = depthBits;
263 pfd.cStencilBits = stencilBits;
264 pfd.iLayerType = PFD_MAIN_PLANE;
266 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
268 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
269 ERR("Can't find a suitable iPixelFormat\n");
273 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
274 res = SetPixelFormat(hdc, iPixelFormat, NULL);
276 int oldPixelFormat = GetPixelFormat(hdc);
279 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
280 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
281 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
284 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
292 ctx = pwglCreateContext(hdc);
293 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
296 ERR("Failed to create a WGL context\n");
298 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
299 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
303 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
305 ERR("Failed to add the newly created context to the context list\n");
306 pwglDeleteContext(ctx);
308 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
309 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
313 ret->surface = (IWineD3DSurface *) target;
314 ret->isPBuffer = create_pbuffer;
315 ret->tid = GetCurrentThreadId();
317 TRACE("Successfully created new context %p\n", ret);
319 /* Set up the context defaults */
320 oldCtx = pwglGetCurrentContext();
321 oldDrawable = pwglGetCurrentDC();
322 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
323 ERR("Cannot activate context to set up defaults\n");
328 TRACE("Setting up the screen\n");
329 /* Clear the screen */
330 glClearColor(1.0, 0.0, 0.0, 0.0);
331 checkGLcall("glClearColor");
334 glClearStencil(0xffff);
336 checkGLcall("glClear");
338 glColor3f(1.0, 1.0, 1.0);
339 checkGLcall("glColor3f");
341 glEnable(GL_LIGHTING);
342 checkGLcall("glEnable");
344 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
345 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
347 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
348 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
350 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
351 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
353 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
354 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
355 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
356 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
358 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
359 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
360 * and textures in DIB sections(due to the memory protection).
362 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
363 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
365 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
366 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
367 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
368 * GL_VERTEX_BLEND_ARB isn't enabled too
370 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
371 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
373 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
374 glEnable(GL_TEXTURE_SHADER_NV);
375 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
377 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
378 * the previous texture where to source the offset from is always unit - 1.
380 for(s = 1; s < GL_LIMITS(textures); s++) {
381 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
382 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
383 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
386 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
387 for(s = 0; s < GL_LIMITS(textures); s++) {
388 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
389 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
390 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
395 if(oldDrawable && oldCtx) {
396 pwglMakeCurrent(oldDrawable, oldCtx);
403 /*****************************************************************************
404 * RemoveContextFromArray
406 * Removes a context from the context manager. The opengl context is not
407 * destroyed or unset. context is not a valid pointer after that call.
409 * Similar to the former call this isn't a performance critical function. A
410 * helper function for DestroyContext.
413 * This: Device to activate the context for
414 * context: Context to remove
416 *****************************************************************************/
417 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
419 WineD3DContext **oldArray = This->contexts;
421 TRACE("Removing ctx %p\n", context);
425 if(This->numContexts) {
426 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
427 if(!This->contexts) {
428 ERR("Cannot allocate a new context array, PANIC!!!\n");
431 for(s = 0; s < This->numContexts; s++) {
432 if(oldArray[s] == context) continue;
433 This->contexts[t] = oldArray[s];
437 This->contexts = NULL;
440 HeapFree(GetProcessHeap(), 0, context);
441 HeapFree(GetProcessHeap(), 0, oldArray);
444 /*****************************************************************************
447 * Destroys a wineD3DContext
450 * This: Device to activate the context for
451 * context: Context to destroy
453 *****************************************************************************/
454 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
456 /* check that we are the current context first */
457 TRACE("Destroying ctx %p\n", context);
458 if(pwglGetCurrentContext() == context->glCtx){
459 pwglMakeCurrent(NULL, NULL);
462 if(context->isPBuffer) {
463 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
464 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
465 } else ReleaseDC(context->win_handle, context->hdc);
466 pwglDeleteContext(context->glCtx);
468 RemoveContextFromArray(This, context);
471 /*****************************************************************************
474 * Sets up a context for DirectDraw blitting.
475 * All texture units are disabled, except unit 0
476 * Texture unit 0 is activted where GL_TEXTURE_2D is activated
477 * fog, lighting, blending, alpha test, z test, scissor test, culling diabled
478 * color writing enabled for all channels
479 * register combiners disabled, shaders disabled
480 * world matris is set to identity, texture matrix 0 too
481 * projection matrix is setup for drawing screen coordinates
484 * This: Device to activate the context for
485 * context: Context to setup
486 * width: render target width
487 * height: render target height
489 *****************************************************************************/
490 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
493 TRACE("Setting up context %p for blitting\n", context);
494 if(context->last_was_blit) {
495 TRACE("Context is already set up for blitting, nothing to do\n");
498 context->last_was_blit = TRUE;
500 /* TODO: Use a display list */
502 /* Disable shaders */
503 This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
504 Context_MarkStateDirty(context, STATE_VSHADER);
505 Context_MarkStateDirty(context, STATE_PIXELSHADER);
507 /* Disable all textures. The caller can then bind a texture it wants to blit
510 if(GL_SUPPORT(NV_REGISTER_COMBINERS)) {
511 glDisable(GL_REGISTER_COMBINERS_NV);
512 checkGLcall("glDisable(GL_REGISTER_COMBINERS_NV)");
514 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
515 /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
516 * function texture unit. No need to care for higher samplers
518 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
519 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
520 checkGLcall("glActiveTextureARB");
522 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
523 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
524 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
526 glDisable(GL_TEXTURE_3D);
527 checkGLcall("glDisable GL_TEXTURE_3D");
528 glDisable(GL_TEXTURE_2D);
529 checkGLcall("glDisable GL_TEXTURE_2D");
531 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
532 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
534 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
535 Context_MarkStateDirty(context, STATE_SAMPLER(i));
537 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
538 checkGLcall("glActiveTextureARB");
540 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
541 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
542 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
544 glDisable(GL_TEXTURE_3D);
545 checkGLcall("glDisable GL_TEXTURE_3D");
546 glEnable(GL_TEXTURE_2D);
547 checkGLcall("glEnable GL_TEXTURE_2D");
549 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
551 glMatrixMode(GL_TEXTURE);
552 checkGLcall("glMatrixMode(GL_TEXTURE)");
554 checkGLcall("glLoadIdentity()");
555 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0));
557 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
558 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
559 GL_TEXTURE_LOD_BIAS_EXT,
561 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
563 Context_MarkStateDirty(context, STATE_SAMPLER(0));
564 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP));
566 /* Other misc states */
567 glDisable(GL_ALPHA_TEST);
568 checkGLcall("glDisable(GL_ALPHA_TEST)");
569 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE));
570 glDisable(GL_LIGHTING);
571 checkGLcall("glDisable GL_LIGHTING");
572 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING));
573 glDisable(GL_DEPTH_TEST);
574 checkGLcall("glDisable GL_DEPTH_TEST");
575 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE));
577 checkGLcall("glDisable GL_FOG");
578 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE));
580 checkGLcall("glDisable GL_BLEND");
581 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE));
582 glDisable(GL_CULL_FACE);
583 checkGLcall("glDisable GL_CULL_FACE");
584 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE));
585 glDisable(GL_STENCIL_TEST);
586 checkGLcall("glDisable GL_STENCIL_TEST");
587 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE));
588 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
589 glDisable(GL_POINT_SPRITE_ARB);
590 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
591 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE));
593 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
594 checkGLcall("glColorMask");
595 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING));
596 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
597 glDisable(GL_COLOR_SUM_EXT);
598 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE));
599 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
601 if (GL_SUPPORT(NV_REGISTER_COMBINERS)) {
602 GL_EXTCALL(glFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB));
603 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE));
604 checkGLcall("glFinalCombinerInputNV");
607 /* Setup transforms */
608 glMatrixMode(GL_MODELVIEW);
609 checkGLcall("glMatrixMode(GL_MODELVIEW)");
611 checkGLcall("glLoadIdentity()");
612 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)));
614 glMatrixMode(GL_PROJECTION);
615 checkGLcall("glMatrixMode(GL_PROJECTION)");
617 checkGLcall("glLoadIdentity()");
618 glOrtho(0, width, height, 0, 0.0, -1.0);
619 checkGLcall("glOrtho");
620 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION));
622 context->last_was_rhw = TRUE;
623 Context_MarkStateDirty(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
625 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
626 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
627 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
628 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
629 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
630 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
631 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING));
633 glViewport(0, 0, width, height);
634 checkGLcall("glViewport");
635 Context_MarkStateDirty(context, STATE_VIEWPORT);
637 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
638 glDisable(GL_TEXTURE_SHADER_NV);
639 checkGLcall("glDisable(GL_TEXTURE_SHADER_NV)");
643 /*****************************************************************************
644 * findThreadContextForSwapChain
646 * Searches a swapchain for all contexts and picks one for the thread tid.
647 * If none can be found the swapchain is requested to create a new context
649 *****************************************************************************/
650 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
653 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
654 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
655 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
660 /* Create a new context for the thread */
661 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
664 /*****************************************************************************
667 * Finds a context for the current render target and thread
670 * target: Render target to find the context for
671 * tid: Thread to activate the context for
673 * Returns: The needed context
675 *****************************************************************************/
676 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
677 IWineD3DSwapChain *swapchain = NULL;
679 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
680 WineD3DContext *context = This->activeContext;
681 BOOL oldRenderOffscreen = This->render_offscreen;
683 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
684 if(hr == WINED3D_OK && swapchain) {
685 TRACE("Rendering onscreen\n");
687 context = findThreadContextForSwapChain(swapchain, tid);
689 This->render_offscreen = FALSE;
690 /* The context != This->activeContext will catch a NOP context change. This can occur
691 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
692 * rendering. No context change is needed in that case
695 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
696 if(((IWineD3DSwapChainImpl *) swapchain)->backBuffer) {
697 glDrawBuffer(GL_BACK);
698 checkGLcall("glDrawBuffer(GL_BACK)");
700 glDrawBuffer(GL_FRONT);
701 checkGLcall("glDrawBuffer(GL_FRONT)");
703 } else if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
704 if(This->pbufferContext && tid == This->pbufferContext->tid) {
705 This->pbufferContext->tid = 0;
708 IWineD3DSwapChain_Release(swapchain);
710 if(oldRenderOffscreen) {
711 Context_MarkStateDirty(context, WINED3DTS_PROJECTION);
712 Context_MarkStateDirty(context, STATE_VDECL);
713 Context_MarkStateDirty(context, STATE_VIEWPORT);
714 Context_MarkStateDirty(context, STATE_SCISSORRECT);
715 Context_MarkStateDirty(context, STATE_FRONTFACE);
719 TRACE("Rendering offscreen\n");
720 This->render_offscreen = TRUE;
722 switch(wined3d_settings.offscreen_rendering_mode) {
724 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
725 if(This->activeContext && tid == This->lastThread) {
726 context = This->activeContext;
728 /* This may happen if the app jumps streight into offscreen rendering
729 * Start using the context of the primary swapchain. tid == 0 is no problem
730 * for findThreadContextForSwapChain.
732 * Can also happen on thread switches - in that case findThreadContextForSwapChain
733 * is perfect to call.
735 context = findThreadContextForSwapChain(This->swapchains[0], tid);
741 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
742 if(This->pbufferContext == NULL ||
743 This->pbufferWidth < targetimpl->currentDesc.Width ||
744 This->pbufferHeight < targetimpl->currentDesc.Height) {
745 if(This->pbufferContext) {
746 DestroyContext(This, This->pbufferContext);
749 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
750 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
752 This->pbufferContext = CreateContext(This, targetimpl,
753 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
754 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
755 This->pbufferWidth = targetimpl->currentDesc.Width;
756 This->pbufferHeight = targetimpl->currentDesc.Height;
759 if(This->pbufferContext) {
760 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
761 FIXME("The PBuffr context is only supported for one thread for now!\n");
763 This->pbufferContext->tid = tid;
764 context = This->pbufferContext;
767 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
768 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
773 /* Stay with the currently active context for back buffer rendering */
774 if(This->activeContext && tid == This->lastThread) {
775 context = This->activeContext;
777 /* This may happen if the app jumps streight into offscreen rendering
778 * Start using the context of the primary swapchain. tid == 0 is no problem
779 * for findThreadContextForSwapChain.
781 * Can also happen on thread switches - in that case findThreadContextForSwapChain
782 * is perfect to call.
784 context = findThreadContextForSwapChain(This->swapchains[0], tid);
786 glDrawBuffer(This->offscreenBuffer);
787 checkGLcall("glDrawBuffer(This->offscreenBuffer)");
791 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
792 /* Make sure we have a OpenGL texture name so the PreLoad() used to read the buffer
793 * back when we are done won't mark us dirty.
795 IWineD3DSurface_PreLoad(target);
798 if(!oldRenderOffscreen) {
799 Context_MarkStateDirty(context, WINED3DTS_PROJECTION);
800 Context_MarkStateDirty(context, STATE_VDECL);
801 Context_MarkStateDirty(context, STATE_VIEWPORT);
802 Context_MarkStateDirty(context, STATE_SCISSORRECT);
803 Context_MarkStateDirty(context, STATE_FRONTFACE);
807 BOOL oldInDraw = This->isInDraw;
809 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
810 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
811 * when using offscreen rendering with multithreading
813 This->isInDraw = TRUE;
815 /* Do that before switching the context:
816 * Read the back buffer of the old drawable into the destination texture
818 IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
820 /* Assume that the drawable will be modified by some other things now */
821 ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->Flags &= ~SFLAG_INDRAWABLE;
823 This->isInDraw = oldInDraw;
826 if(oldRenderOffscreen != This->render_offscreen && This->depth_copy_state != WINED3D_DCS_NO_COPY) {
827 This->depth_copy_state = WINED3D_DCS_COPY;
832 /*****************************************************************************
835 * Finds a rendering context and drawable matching the device and render
836 * target for the current thread, activates them and puts them into the
840 * This: Device to activate the context for
841 * target: Requested render target
842 * usage: Prepares the context for blitting, drawing or other actions
844 *****************************************************************************/
845 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
846 DWORD tid = GetCurrentThreadId();
848 DWORD dirtyState, idx;
850 WineD3DContext *context;
852 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
854 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
855 context = FindContext(This, target, tid);
856 This->lastActiveRenderTarget = target;
857 This->lastThread = tid;
859 /* Stick to the old context */
860 context = This->activeContext;
863 /* Activate the opengl context */
864 if(context != This->activeContext) {
866 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
867 ret = pwglMakeCurrent(context->hdc, context->glCtx);
869 ERR("Failed to activate the new context\n");
871 This->activeContext = context;
874 /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
877 case CTXUSAGE_RESOURCELOAD:
878 /* This does not require any special states to be set up */
882 if(context->last_was_blit && GL_SUPPORT(NV_TEXTURE_SHADER2)) {
883 glEnable(GL_TEXTURE_SHADER_NV);
884 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
887 glEnable(GL_SCISSOR_TEST);
888 checkGLcall("glEnable GL_SCISSOR_TEST");
889 context->last_was_blit = FALSE;
890 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
891 Context_MarkStateDirty(context, STATE_SCISSORRECT);
894 case CTXUSAGE_DRAWPRIM:
895 /* This needs all dirty states applied */
896 if(context->last_was_blit && GL_SUPPORT(NV_TEXTURE_SHADER2)) {
897 glEnable(GL_TEXTURE_SHADER_NV);
898 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
901 IWineD3DDeviceImpl_FindTexUnitMap(This);
903 for(i=0; i < context->numDirtyEntries; i++) {
904 dirtyState = context->dirtyArray[i];
905 idx = dirtyState >> 5;
906 shift = dirtyState & 0x1f;
907 context->isStateDirty[idx] &= ~(1 << shift);
908 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
910 context->numDirtyEntries = 0; /* This makes the whole list clean */
911 context->last_was_blit = FALSE;
915 SetupForBlit(This, context,
916 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
917 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
921 FIXME("Unexpected context usage requested\n");