push 8c61147e396035865ef2da2e6aa2d0f3b0907179
[wine/hacks.git] / dlls / wined3d / context.c
blob172cd6b01a56c2a7ea551cb212c4e78689ca2005
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 (*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 void context_set_last_device(IWineD3DDeviceImpl *device)
41 last_device = device;
44 /* FBO helper functions */
46 /* GL locking is done by the caller */
47 void context_bind_fbo(struct WineD3DContext *context, GLenum target, GLuint *fbo)
49 const struct wined3d_gl_info *gl_info = context->gl_info;
50 GLuint f;
52 if (!fbo)
54 f = 0;
56 else
58 if (!*fbo)
60 GL_EXTCALL(glGenFramebuffersEXT(1, fbo));
61 checkGLcall("glGenFramebuffersEXT()");
62 TRACE("Created FBO %u.\n", *fbo);
64 f = *fbo;
67 switch (target)
69 case GL_READ_FRAMEBUFFER_EXT:
70 if (context->fbo_read_binding == f) return;
71 context->fbo_read_binding = f;
72 break;
74 case GL_DRAW_FRAMEBUFFER_EXT:
75 if (context->fbo_draw_binding == f) return;
76 context->fbo_draw_binding = f;
77 break;
79 case GL_FRAMEBUFFER_EXT:
80 if (context->fbo_read_binding == f
81 && context->fbo_draw_binding == f) return;
82 context->fbo_read_binding = f;
83 context->fbo_draw_binding = f;
84 break;
86 default:
87 FIXME("Unhandled target %#x.\n", target);
88 break;
91 GL_EXTCALL(glBindFramebufferEXT(target, f));
92 checkGLcall("glBindFramebuffer()");
95 /* GL locking is done by the caller */
96 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info)
98 unsigned int i;
100 for (i = 0; i < GL_LIMITS(buffers); ++i)
102 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, 0, 0));
103 checkGLcall("glFramebufferTexture2D()");
105 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
106 checkGLcall("glFramebufferTexture2D()");
108 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
109 checkGLcall("glFramebufferTexture2D()");
112 /* GL locking is done by the caller */
113 static void context_destroy_fbo(struct WineD3DContext *context, GLuint *fbo)
115 const struct wined3d_gl_info *gl_info = context->gl_info;
117 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, fbo);
118 context_clean_fbo_attachments(gl_info);
119 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, NULL);
121 GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo));
122 checkGLcall("glDeleteFramebuffers()");
125 /* GL locking is done by the caller */
126 static void context_apply_attachment_filter_states(IWineD3DSurface *surface, BOOL force_preload)
128 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
129 IWineD3DDeviceImpl *device = surface_impl->resource.wineD3DDevice;
130 IWineD3DBaseTextureImpl *texture_impl;
131 BOOL update_minfilter = FALSE;
132 BOOL update_magfilter = FALSE;
134 /* Update base texture states array */
135 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
137 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
138 || texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
140 texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
141 texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
142 update_minfilter = TRUE;
145 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
147 texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
148 update_magfilter = TRUE;
151 if (texture_impl->baseTexture.bindCount)
153 WARN("Render targets should not be bound to a sampler\n");
154 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(texture_impl->baseTexture.sampler));
157 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
160 if (update_minfilter || update_magfilter || force_preload)
162 GLenum target, bind_target;
163 GLint old_binding;
165 target = surface_impl->texture_target;
166 if (target == GL_TEXTURE_2D)
168 bind_target = GL_TEXTURE_2D;
169 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
170 } else if (target == GL_TEXTURE_RECTANGLE_ARB) {
171 bind_target = GL_TEXTURE_RECTANGLE_ARB;
172 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
173 } else {
174 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
175 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
178 surface_internal_preload(surface, SRGB_RGB);
180 glBindTexture(bind_target, surface_impl->texture_name);
181 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
182 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
183 glBindTexture(bind_target, old_binding);
186 checkGLcall("apply_attachment_filter_states()");
189 /* GL locking is done by the caller */
190 void context_attach_depth_stencil_fbo(struct WineD3DContext *context,
191 GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
193 IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
194 const struct wined3d_gl_info *gl_info = context->gl_info;
196 TRACE("Attach depth stencil %p\n", depth_stencil);
198 if (depth_stencil)
200 DWORD format_flags = depth_stencil_impl->resource.format_desc->Flags;
202 if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
204 if (format_flags & WINED3DFMT_FLAG_DEPTH)
206 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT,
207 GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
208 checkGLcall("glFramebufferRenderbufferEXT()");
211 if (format_flags & WINED3DFMT_FLAG_STENCIL)
213 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_STENCIL_ATTACHMENT_EXT,
214 GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
215 checkGLcall("glFramebufferRenderbufferEXT()");
218 else
220 context_apply_attachment_filter_states(depth_stencil, TRUE);
222 if (format_flags & WINED3DFMT_FLAG_DEPTH)
224 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT,
225 depth_stencil_impl->texture_target, depth_stencil_impl->texture_name,
226 depth_stencil_impl->texture_level));
227 checkGLcall("glFramebufferTexture2DEXT()");
230 if (format_flags & WINED3DFMT_FLAG_STENCIL)
232 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_STENCIL_ATTACHMENT_EXT,
233 depth_stencil_impl->texture_target, depth_stencil_impl->texture_name,
234 depth_stencil_impl->texture_level));
235 checkGLcall("glFramebufferTexture2DEXT()");
239 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
241 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
242 checkGLcall("glFramebufferTexture2DEXT()");
245 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
247 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
248 checkGLcall("glFramebufferTexture2DEXT()");
251 else
253 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
254 checkGLcall("glFramebufferTexture2DEXT()");
256 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
257 checkGLcall("glFramebufferTexture2DEXT()");
261 /* GL locking is done by the caller */
262 void context_attach_surface_fbo(const struct WineD3DContext *context,
263 GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
265 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
266 const struct wined3d_gl_info *gl_info = context->gl_info;
268 TRACE("Attach surface %p to %u\n", surface, idx);
270 if (surface)
272 context_apply_attachment_filter_states(surface, TRUE);
274 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, surface_impl->texture_target,
275 surface_impl->texture_name, surface_impl->texture_level));
276 checkGLcall("glFramebufferTexture2DEXT()");
277 } else {
278 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, GL_TEXTURE_2D, 0, 0));
279 checkGLcall("glFramebufferTexture2DEXT()");
283 /* GL locking is done by the caller */
284 static void context_check_fbo_status(struct WineD3DContext *context)
286 const struct wined3d_gl_info *gl_info = context->gl_info;
287 GLenum status;
289 status = GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
290 if (status == GL_FRAMEBUFFER_COMPLETE_EXT)
292 TRACE("FBO complete\n");
293 } else {
294 IWineD3DSurfaceImpl *attachment;
295 unsigned int i;
296 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
298 /* Dump the FBO attachments */
299 for (i = 0; i < GL_LIMITS(buffers); ++i)
301 attachment = (IWineD3DSurfaceImpl *)context->current_fbo->render_targets[i];
302 if (attachment)
304 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
305 i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
306 attachment->pow2Width, attachment->pow2Height);
309 attachment = (IWineD3DSurfaceImpl *)context->current_fbo->depth_stencil;
310 if (attachment)
312 FIXME("\tDepth attachment: (%p) %s %ux%u\n",
313 attachment, debug_d3dformat(attachment->resource.format_desc->format),
314 attachment->pow2Width, attachment->pow2Height);
319 static struct fbo_entry *context_create_fbo_entry(struct WineD3DContext *context)
321 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
322 const struct wined3d_gl_info *gl_info = context->gl_info;
323 struct fbo_entry *entry;
325 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
326 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
327 memcpy(entry->render_targets, device->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
328 entry->depth_stencil = device->stencilBufferTarget;
329 entry->attached = FALSE;
330 entry->id = 0;
332 return entry;
335 /* GL locking is done by the caller */
336 static void context_reuse_fbo_entry(struct WineD3DContext *context, struct fbo_entry *entry)
338 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
339 const struct wined3d_gl_info *gl_info = context->gl_info;
341 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, &entry->id);
342 context_clean_fbo_attachments(gl_info);
344 memcpy(entry->render_targets, device->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
345 entry->depth_stencil = device->stencilBufferTarget;
346 entry->attached = FALSE;
349 /* GL locking is done by the caller */
350 static void context_destroy_fbo_entry(struct WineD3DContext *context, struct fbo_entry *entry)
352 if (entry->id)
354 TRACE("Destroy FBO %d\n", entry->id);
355 context_destroy_fbo(context, &entry->id);
357 --context->fbo_entry_count;
358 list_remove(&entry->entry);
359 HeapFree(GetProcessHeap(), 0, entry->render_targets);
360 HeapFree(GetProcessHeap(), 0, entry);
364 /* GL locking is done by the caller */
365 static struct fbo_entry *context_find_fbo_entry(struct WineD3DContext *context)
367 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
368 const struct wined3d_gl_info *gl_info = context->gl_info;
369 struct fbo_entry *entry;
371 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
373 if (!memcmp(entry->render_targets, device->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets))
374 && entry->depth_stencil == device->stencilBufferTarget)
376 list_remove(&entry->entry);
377 list_add_head(&context->fbo_list, &entry->entry);
378 return entry;
382 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
384 entry = context_create_fbo_entry(context);
385 list_add_head(&context->fbo_list, &entry->entry);
386 ++context->fbo_entry_count;
388 else
390 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
391 context_reuse_fbo_entry(context, entry);
392 list_remove(&entry->entry);
393 list_add_head(&context->fbo_list, &entry->entry);
396 return entry;
399 /* GL locking is done by the caller */
400 static void context_apply_fbo_entry(struct WineD3DContext *context, struct fbo_entry *entry)
402 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
403 const struct wined3d_gl_info *gl_info = context->gl_info;
404 unsigned int i;
406 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, &entry->id);
408 if (!entry->attached)
410 /* Apply render targets */
411 for (i = 0; i < GL_LIMITS(buffers); ++i)
413 IWineD3DSurface *render_target = device->render_targets[i];
414 context_attach_surface_fbo(context, GL_FRAMEBUFFER_EXT, i, render_target);
417 /* Apply depth targets */
418 if (device->stencilBufferTarget)
420 unsigned int w = ((IWineD3DSurfaceImpl *)device->render_targets[0])->pow2Width;
421 unsigned int h = ((IWineD3DSurfaceImpl *)device->render_targets[0])->pow2Height;
423 surface_set_compatible_renderbuffer(device->stencilBufferTarget, w, h);
425 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER_EXT, device->stencilBufferTarget, TRUE);
427 entry->attached = TRUE;
428 } else {
429 for (i = 0; i < GL_LIMITS(buffers); ++i)
431 if (device->render_targets[i])
432 context_apply_attachment_filter_states(device->render_targets[i], FALSE);
434 if (device->stencilBufferTarget)
435 context_apply_attachment_filter_states(device->stencilBufferTarget, FALSE);
438 for (i = 0; i < GL_LIMITS(buffers); ++i)
440 if (device->render_targets[i])
441 device->draw_buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
442 else
443 device->draw_buffers[i] = GL_NONE;
447 /* GL locking is done by the caller */
448 static void context_apply_fbo_state(struct WineD3DContext *context)
450 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
452 if (device->render_offscreen)
454 context->current_fbo = context_find_fbo_entry(context);
455 context_apply_fbo_entry(context, context->current_fbo);
456 } else {
457 context->current_fbo = NULL;
458 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, NULL);
461 context_check_fbo_status(context);
464 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
466 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
467 UINT i;
469 switch(type)
471 case WINED3DRTYPE_SURFACE:
473 if ((IWineD3DSurface *)resource == This->lastActiveRenderTarget)
475 IWineD3DSwapChainImpl *swapchain;
477 TRACE("Last active render target destroyed.\n");
479 /* Find a replacement surface for the currently active back
480 * buffer. The context manager does not do NULL checks, so
481 * switch to a valid target as long as the currently set
482 * surface is still valid. Use the surface of the implicit
483 * swpchain. If that is the same as the destroyed surface the
484 * device is destroyed and the lastActiveRenderTarget member
485 * shouldn't matter. */
486 swapchain = This->swapchains ? (IWineD3DSwapChainImpl *)This->swapchains[0] : NULL;
487 if (swapchain)
489 if (swapchain->backBuffer && swapchain->backBuffer[0] != (IWineD3DSurface *)resource)
491 TRACE("Activating primary back buffer.\n");
492 ActivateContext(This, swapchain->backBuffer[0], CTXUSAGE_RESOURCELOAD);
494 else if (!swapchain->backBuffer && swapchain->frontBuffer != (IWineD3DSurface *)resource)
496 /* Single buffering environment */
497 TRACE("Activating primary front buffer.\n");
499 ActivateContext(This, swapchain->frontBuffer, CTXUSAGE_RESOURCELOAD);
501 else
503 /* Implicit render target destroyed, that means the
504 * device is being destroyed whatever we set here, it
505 * shouldn't matter. */
506 TRACE("Device is being destroyed, setting lastActiveRenderTarget to 0xdeadbabe.\n");
508 This->lastActiveRenderTarget = (IWineD3DSurface *) 0xdeadbabe;
511 else
513 WARN("Render target set, but swapchain does not exist!\n");
515 /* May happen during ddraw uninitialization. */
516 This->lastActiveRenderTarget = (IWineD3DSurface *)0xdeadcafe;
519 else if (This->d3d_initialized)
521 ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
524 for (i = 0; i < This->numContexts; ++i)
526 WineD3DContext *context = This->contexts[i];
527 const struct wined3d_gl_info *gl_info = context->gl_info;
528 struct fbo_entry *entry, *entry2;
530 ENTER_GL();
532 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
534 BOOL destroyed = FALSE;
535 UINT j;
537 for (j = 0; !destroyed && j < GL_LIMITS(buffers); ++j)
539 if (entry->render_targets[j] == (IWineD3DSurface *)resource)
541 context_destroy_fbo_entry(context, entry);
542 destroyed = TRUE;
546 if (!destroyed && entry->depth_stencil == (IWineD3DSurface *)resource)
547 context_destroy_fbo_entry(context, entry);
550 LEAVE_GL();
553 break;
556 default:
557 break;
561 /*****************************************************************************
562 * Context_MarkStateDirty
564 * Marks a state in a context dirty. Only one context, opposed to
565 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
566 * contexts
568 * Params:
569 * context: Context to mark the state dirty in
570 * state: State to mark dirty
571 * StateTable: Pointer to the state table in use(for state grouping)
573 *****************************************************************************/
574 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
575 DWORD rep = StateTable[state].representative;
576 DWORD idx;
577 BYTE shift;
579 if(!rep || isStateDirty(context, rep)) return;
581 context->dirtyArray[context->numDirtyEntries++] = rep;
582 idx = rep >> 5;
583 shift = rep & 0x1f;
584 context->isStateDirty[idx] |= (1 << shift);
587 /*****************************************************************************
588 * AddContextToArray
590 * Adds a context to the context array. Helper function for CreateContext
592 * This method is not called in performance-critical code paths, only when a
593 * new render target or swapchain is created. Thus performance is not an issue
594 * here.
596 * Params:
597 * This: Device to add the context for
598 * hdc: device context
599 * glCtx: WGL context to add
600 * pbuffer: optional pbuffer used with this context
602 *****************************************************************************/
603 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
604 WineD3DContext **oldArray = This->contexts;
605 DWORD state;
607 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
608 if(This->contexts == NULL) {
609 ERR("Unable to grow the context array\n");
610 This->contexts = oldArray;
611 return NULL;
613 if(oldArray) {
614 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
617 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
618 if(This->contexts[This->numContexts] == NULL) {
619 ERR("Unable to allocate a new context\n");
620 HeapFree(GetProcessHeap(), 0, This->contexts);
621 This->contexts = oldArray;
622 return NULL;
625 This->contexts[This->numContexts]->hdc = hdc;
626 This->contexts[This->numContexts]->glCtx = glCtx;
627 This->contexts[This->numContexts]->pbuffer = pbuffer;
628 This->contexts[This->numContexts]->win_handle = win_handle;
629 HeapFree(GetProcessHeap(), 0, oldArray);
631 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
633 for(state = 0; state <= STATE_HIGHEST; state++) {
634 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
637 This->numContexts++;
638 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
639 return This->contexts[This->numContexts - 1];
642 /* This function takes care of WineD3D pixel format selection. */
643 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
644 const struct GlPixelFormatDesc *color_format_desc, const struct GlPixelFormatDesc *ds_format_desc,
645 BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
647 int iPixelFormat=0;
648 unsigned int matchtry;
649 short redBits, greenBits, blueBits, alphaBits, colorBits;
650 short depthBits=0, stencilBits=0;
652 struct match_type {
653 BOOL require_aux;
654 BOOL exact_alpha;
655 BOOL exact_color;
656 } matches[] = {
657 /* First, try without alpha match buffers. MacOS supports aux buffers only
658 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
659 * Then try without aux buffers - this is the most common cause for not
660 * finding a pixel format. Also some drivers(the open source ones)
661 * only offer 32 bit ARB pixel formats. First try without an exact alpha
662 * match, then try without an exact alpha and color match.
664 { TRUE, TRUE, TRUE },
665 { TRUE, FALSE, TRUE },
666 { FALSE, TRUE, TRUE },
667 { FALSE, FALSE, TRUE },
668 { TRUE, FALSE, FALSE },
669 { FALSE, FALSE, FALSE },
672 int i = 0;
673 int nCfgs = This->adapter->nCfgs;
675 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
676 debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
677 auxBuffers, numSamples, pbuffer, findCompatible);
679 if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
681 ERR("Unable to get color bits for format %s (%#x)!\n",
682 debug_d3dformat(color_format_desc->format), color_format_desc->format);
683 return 0;
686 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
687 * You are able to add a depth + stencil surface at a later stage when you need it.
688 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
689 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
690 * context, need torecreate shaders, textures and other resources.
692 * The context manager already takes care of the state problem and for the other tasks code from Reset
693 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
694 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
695 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
696 * issue needs to be fixed. */
697 if (ds_format_desc->format != WINED3DFMT_D24S8)
699 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
700 ds_format_desc = getFormatDescEntry(WINED3DFMT_D24S8, &This->adapter->gl_info);
703 getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
705 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
706 for(i=0; i<nCfgs; i++) {
707 BOOL exactDepthMatch = TRUE;
708 WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
710 /* For now only accept RGBA formats. Perhaps some day we will
711 * allow floating point formats for pbuffers. */
712 if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
713 continue;
715 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
716 if(!pbuffer && !(cfg->windowDrawable && cfg->doubleBuffer))
717 continue;
719 /* We like to have aux buffers in backbuffer mode */
720 if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
721 continue;
723 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
724 if(pbuffer && (!cfg->pbufferDrawable || cfg->doubleBuffer))
725 continue;
727 if(matches[matchtry].exact_color) {
728 if(cfg->redSize != redBits)
729 continue;
730 if(cfg->greenSize != greenBits)
731 continue;
732 if(cfg->blueSize != blueBits)
733 continue;
734 } else {
735 if(cfg->redSize < redBits)
736 continue;
737 if(cfg->greenSize < greenBits)
738 continue;
739 if(cfg->blueSize < blueBits)
740 continue;
742 if(matches[matchtry].exact_alpha) {
743 if(cfg->alphaSize != alphaBits)
744 continue;
745 } else {
746 if(cfg->alphaSize < alphaBits)
747 continue;
750 /* We try to locate a format which matches our requirements exactly. In case of
751 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
752 if(cfg->depthSize < depthBits)
753 continue;
754 else if(cfg->depthSize > depthBits)
755 exactDepthMatch = FALSE;
757 /* In all cases make sure the number of stencil bits matches our requirements
758 * even when we don't need stencil because it could affect performance EXCEPT
759 * on cards which don't offer depth formats without stencil like the i915 drivers
760 * on Linux. */
761 if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
762 continue;
764 /* Check multisampling support */
765 if(cfg->numSamples != numSamples)
766 continue;
768 /* When we have passed all the checks then we have found a format which matches our
769 * requirements. Note that we only check for a limit number of capabilities right now,
770 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
771 * can still differ in things like multisampling, stereo, SRGB and other flags.
774 /* Exit the loop as we have found a format :) */
775 if(exactDepthMatch) {
776 iPixelFormat = cfg->iPixelFormat;
777 break;
778 } else if(!iPixelFormat) {
779 /* In the end we might end up with a format which doesn't exactly match our depth
780 * requirements. Accept the first format we found because formats with higher iPixelFormat
781 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
782 iPixelFormat = cfg->iPixelFormat;
787 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
788 if(!iPixelFormat && !findCompatible) {
789 ERR("Can't find a suitable iPixelFormat\n");
790 return FALSE;
791 } else if(!iPixelFormat) {
792 PIXELFORMATDESCRIPTOR pfd;
794 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
795 /* PixelFormat selection */
796 ZeroMemory(&pfd, sizeof(pfd));
797 pfd.nSize = sizeof(pfd);
798 pfd.nVersion = 1;
799 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
800 pfd.iPixelType = PFD_TYPE_RGBA;
801 pfd.cAlphaBits = alphaBits;
802 pfd.cColorBits = colorBits;
803 pfd.cDepthBits = depthBits;
804 pfd.cStencilBits = stencilBits;
805 pfd.iLayerType = PFD_MAIN_PLANE;
807 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
808 if(!iPixelFormat) {
809 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
810 ERR("Can't find a suitable iPixelFormat\n");
811 return FALSE;
815 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
816 iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
817 return iPixelFormat;
820 /*****************************************************************************
821 * CreateContext
823 * Creates a new context for a window, or a pbuffer context.
825 * * Params:
826 * This: Device to activate the context for
827 * target: Surface this context will render to
828 * win_handle: handle to the window which we are drawing to
829 * create_pbuffer: tells whether to create a pbuffer or not
830 * pPresentParameters: contains the pixelformats to use for onscreen rendering
832 *****************************************************************************/
833 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
834 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
835 HPBUFFERARB pbuffer = NULL;
836 WineD3DContext *ret = NULL;
837 unsigned int s;
838 HGLRC ctx;
839 HDC hdc;
841 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
843 if(create_pbuffer) {
844 HDC hdc_parent = GetDC(win_handle);
845 int iPixelFormat = 0;
847 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
848 const struct GlPixelFormatDesc *ds_format_desc = StencilSurface
849 ? ((IWineD3DSurfaceImpl *)StencilSurface)->resource.format_desc
850 : getFormatDescEntry(WINED3DFMT_UNKNOWN, &This->adapter->gl_info);
852 /* Try to find a pixel format with pbuffer support. */
853 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
854 ds_format_desc, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */,
855 FALSE /* findCompatible */);
856 if(!iPixelFormat) {
857 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
859 /* For some reason we weren't able to find a format, try to find something instead of crashing.
860 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
861 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
862 ds_format_desc, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */,
863 TRUE /* findCompatible */);
866 /* This shouldn't happen as ChoosePixelFormat always returns something */
867 if(!iPixelFormat) {
868 ERR("Unable to locate a pixel format for a pbuffer\n");
869 ReleaseDC(win_handle, hdc_parent);
870 goto out;
873 TRACE("Creating a pBuffer drawable for the new context\n");
874 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
875 if(!pbuffer) {
876 ERR("Cannot create a pbuffer\n");
877 ReleaseDC(win_handle, hdc_parent);
878 goto out;
881 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
882 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
883 if(!hdc) {
884 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
885 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
886 ReleaseDC(win_handle, hdc_parent);
887 goto out;
889 ReleaseDC(win_handle, hdc_parent);
890 } else {
891 PIXELFORMATDESCRIPTOR pfd;
892 int iPixelFormat;
893 int res;
894 const struct GlPixelFormatDesc *color_format_desc = target->resource.format_desc;
895 const struct GlPixelFormatDesc *ds_format_desc = getFormatDescEntry(WINED3DFMT_UNKNOWN,
896 &This->adapter->gl_info);
897 BOOL auxBuffers = FALSE;
898 int numSamples = 0;
900 hdc = GetDC(win_handle);
901 if(hdc == NULL) {
902 ERR("Cannot retrieve a device context!\n");
903 goto out;
906 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
907 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
908 auxBuffers = TRUE;
910 if (color_format_desc->format == WINED3DFMT_X4R4G4B4)
911 color_format_desc = getFormatDescEntry(WINED3DFMT_A4R4G4B4, &This->adapter->gl_info);
912 else if (color_format_desc->format == WINED3DFMT_X8R8G8B8)
913 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
916 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
917 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
918 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
919 * a format with 8bit alpha, so request A8R8G8B8. */
920 if (color_format_desc->format == WINED3DFMT_P8)
921 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
923 /* Retrieve the depth stencil format from the present parameters.
924 * The choice of the proper format can give a nice performance boost
925 * in case of GPU limited programs. */
926 if(pPresentParms->EnableAutoDepthStencil) {
927 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
928 ds_format_desc = getFormatDescEntry(pPresentParms->AutoDepthStencilFormat, &This->adapter->gl_info);
931 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
932 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
933 if(!GL_SUPPORT(ARB_MULTISAMPLE))
934 ERR("The program is requesting multisampling without support!\n");
935 else {
936 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
937 numSamples = pPresentParms->MultiSampleType;
941 /* Try to find a pixel format which matches our requirements */
942 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
943 auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
945 /* Try to locate a compatible format if we weren't able to find anything */
946 if(!iPixelFormat) {
947 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
948 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
949 auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
952 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
953 if(!iPixelFormat) {
954 ERR("Can't find a suitable iPixelFormat\n");
955 return FALSE;
958 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
959 res = SetPixelFormat(hdc, iPixelFormat, NULL);
960 if(!res) {
961 int oldPixelFormat = GetPixelFormat(hdc);
963 /* By default WGL doesn't allow pixel format adjustments but we need it here.
964 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
965 * set the pixel format multiple times. Only use it when it is really needed. */
967 if(oldPixelFormat == iPixelFormat) {
968 /* We don't have to do anything as the formats are the same :) */
969 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
970 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
972 if(!res) {
973 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
974 return FALSE;
976 } else if(oldPixelFormat) {
977 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
978 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
979 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
980 } else {
981 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
982 return FALSE;
987 ctx = pwglCreateContext(hdc);
988 if (This->numContexts)
990 if (!pwglShareLists(This->contexts[0]->glCtx, ctx))
992 DWORD err = GetLastError();
993 ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
994 This->contexts[0]->glCtx, ctx, err);
998 if(!ctx) {
999 ERR("Failed to create a WGL context\n");
1000 if(create_pbuffer) {
1001 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
1002 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
1004 goto out;
1006 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
1007 if(!ret) {
1008 ERR("Failed to add the newly created context to the context list\n");
1009 if (!pwglDeleteContext(ctx))
1011 DWORD err = GetLastError();
1012 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, err);
1014 if(create_pbuffer) {
1015 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
1016 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
1018 goto out;
1020 ret->gl_info = &This->adapter->gl_info;
1021 ret->surface = (IWineD3DSurface *) target;
1022 ret->isPBuffer = create_pbuffer;
1023 ret->tid = GetCurrentThreadId();
1024 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
1025 /* Create the dirty constants array and initialize them to dirty */
1026 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1027 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1028 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1029 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1030 memset(ret->vshader_const_dirty, 1,
1031 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1032 memset(ret->pshader_const_dirty, 1,
1033 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1036 TRACE("Successfully created new context %p\n", ret);
1038 list_init(&ret->fbo_list);
1040 /* Set up the context defaults */
1041 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
1042 ERR("Cannot activate context to set up defaults\n");
1043 goto out;
1046 ENTER_GL();
1048 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1050 TRACE("Setting up the screen\n");
1051 /* Clear the screen */
1052 glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1053 checkGLcall("glClearColor");
1054 glClearIndex(0);
1055 glClearDepth(1);
1056 glClearStencil(0xffff);
1058 checkGLcall("glClear");
1060 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1061 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1063 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1064 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1066 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1067 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1069 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
1070 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
1071 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
1072 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
1074 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
1075 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
1076 * and textures in DIB sections(due to the memory protection).
1078 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1079 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1081 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
1082 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
1083 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
1084 * GL_VERTEX_BLEND_ARB isn't enabled too
1086 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1087 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1089 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
1090 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1091 * the previous texture where to source the offset from is always unit - 1.
1093 for(s = 1; s < GL_LIMITS(textures); s++) {
1094 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1095 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1096 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1099 if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
1100 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1101 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1102 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1103 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1104 * is ever assigned.
1106 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1107 * program and the dummy program is destroyed when the context is destroyed.
1109 const char *dummy_program =
1110 "!!ARBfp1.0\n"
1111 "MOV result.color, fragment.color.primary;\n"
1112 "END\n";
1113 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1114 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1115 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1118 for(s = 0; s < GL_LIMITS(point_sprite_units); s++) {
1119 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1120 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1121 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1123 LEAVE_GL();
1125 context_set_last_device(This);
1126 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1128 return ret;
1130 out:
1131 return NULL;
1134 /*****************************************************************************
1135 * RemoveContextFromArray
1137 * Removes a context from the context manager. The opengl context is not
1138 * destroyed or unset. context is not a valid pointer after that call.
1140 * Similar to the former call this isn't a performance critical function. A
1141 * helper function for DestroyContext.
1143 * Params:
1144 * This: Device to activate the context for
1145 * context: Context to remove
1147 *****************************************************************************/
1148 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
1149 WineD3DContext **new_array;
1150 BOOL found = FALSE;
1151 UINT i;
1153 TRACE("Removing ctx %p\n", context);
1155 for (i = 0; i < This->numContexts; ++i)
1157 if (This->contexts[i] == context)
1159 HeapFree(GetProcessHeap(), 0, context);
1160 found = TRUE;
1161 break;
1165 if (!found)
1167 ERR("Context %p doesn't exist in context array\n", context);
1168 return;
1171 while (i < This->numContexts - 1)
1173 This->contexts[i] = This->contexts[i + 1];
1174 ++i;
1177 --This->numContexts;
1178 if (!This->numContexts)
1180 HeapFree(GetProcessHeap(), 0, This->contexts);
1181 This->contexts = NULL;
1182 return;
1185 new_array = HeapReAlloc(GetProcessHeap(), 0, This->contexts, This->numContexts * sizeof(*This->contexts));
1186 if (!new_array)
1188 ERR("Failed to shrink context array. Oh well.\n");
1189 return;
1192 This->contexts = new_array;
1195 /*****************************************************************************
1196 * DestroyContext
1198 * Destroys a wineD3DContext
1200 * Params:
1201 * This: Device to activate the context for
1202 * context: Context to destroy
1204 *****************************************************************************/
1205 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
1206 const struct wined3d_gl_info *gl_info = context->gl_info;
1207 struct fbo_entry *entry, *entry2;
1208 BOOL has_glctx;
1210 TRACE("Destroying ctx %p\n", context);
1212 /* The correct GL context needs to be active to cleanup the GL resources below */
1213 has_glctx = pwglMakeCurrent(context->hdc, context->glCtx);
1214 context_set_last_device(NULL);
1216 if (!has_glctx) WARN("Failed to activate context. Window already destroyed?\n");
1218 ENTER_GL();
1220 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
1221 if (!has_glctx) entry->id = 0;
1222 context_destroy_fbo_entry(context, entry);
1224 if (has_glctx)
1226 if (context->src_fbo)
1228 TRACE("Destroy src FBO %d\n", context->src_fbo);
1229 context_destroy_fbo(context, &context->src_fbo);
1231 if (context->dst_fbo)
1233 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
1234 context_destroy_fbo(context, &context->dst_fbo);
1236 if (context->dummy_arbfp_prog)
1238 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1242 LEAVE_GL();
1244 if (This->activeContext == context)
1246 This->activeContext = NULL;
1247 TRACE("Destroying the active context.\n");
1250 /* Cleanup the GL context */
1251 if (!pwglMakeCurrent(NULL, NULL))
1253 ERR("Failed to disable GL context.\n");
1256 if(context->isPBuffer) {
1257 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
1258 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
1259 } else ReleaseDC(context->win_handle, context->hdc);
1260 pwglDeleteContext(context->glCtx);
1262 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1263 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1264 RemoveContextFromArray(This, context);
1267 /* GL locking is done by the caller */
1268 static inline void set_blit_dimension(UINT width, UINT height) {
1269 glMatrixMode(GL_PROJECTION);
1270 checkGLcall("glMatrixMode(GL_PROJECTION)");
1271 glLoadIdentity();
1272 checkGLcall("glLoadIdentity()");
1273 glOrtho(0, width, height, 0, 0.0, -1.0);
1274 checkGLcall("glOrtho");
1275 glViewport(0, 0, width, height);
1276 checkGLcall("glViewport");
1279 /*****************************************************************************
1280 * SetupForBlit
1282 * Sets up a context for DirectDraw blitting.
1283 * All texture units are disabled, texture unit 0 is set as current unit
1284 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1285 * color writing enabled for all channels
1286 * register combiners disabled, shaders disabled
1287 * world matrix is set to identity, texture matrix 0 too
1288 * projection matrix is setup for drawing screen coordinates
1290 * Params:
1291 * This: Device to activate the context for
1292 * context: Context to setup
1293 * width: render target width
1294 * height: render target height
1296 *****************************************************************************/
1297 /* Context activation is done by the caller. */
1298 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
1299 int i, sampler;
1300 const struct StateEntry *StateTable = This->StateTable;
1301 const struct wined3d_gl_info *gl_info = context->gl_info;
1303 TRACE("Setting up context %p for blitting\n", context);
1304 if(context->last_was_blit) {
1305 if(context->blit_w != width || context->blit_h != height) {
1306 ENTER_GL();
1307 set_blit_dimension(width, height);
1308 LEAVE_GL();
1309 context->blit_w = width; context->blit_h = height;
1310 /* No need to dirtify here, the states are still dirtified because they weren't
1311 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1312 * be set
1315 TRACE("Context is already set up for blitting, nothing to do\n");
1316 return;
1318 context->last_was_blit = TRUE;
1320 /* TODO: Use a display list */
1322 /* Disable shaders */
1323 ENTER_GL();
1324 This->shader_backend->shader_select((IWineD3DDevice *)This, FALSE, FALSE);
1325 LEAVE_GL();
1327 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1328 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1330 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1331 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1332 * which can safely be called from here, we only lock once instead locking/unlocking
1333 * after each GL call.
1335 ENTER_GL();
1337 /* Disable all textures. The caller can then bind a texture it wants to blit
1338 * from
1340 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1341 * function texture unit. No need to care for higher samplers
1343 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
1344 sampler = This->rev_tex_unit_map[i];
1345 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1346 checkGLcall("glActiveTextureARB");
1348 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1349 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1350 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1352 glDisable(GL_TEXTURE_3D);
1353 checkGLcall("glDisable GL_TEXTURE_3D");
1354 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1355 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1356 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1358 glDisable(GL_TEXTURE_2D);
1359 checkGLcall("glDisable GL_TEXTURE_2D");
1361 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1362 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1364 if (sampler != -1) {
1365 if (sampler < MAX_TEXTURES) {
1366 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1368 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1371 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1372 checkGLcall("glActiveTextureARB");
1374 sampler = This->rev_tex_unit_map[0];
1376 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1377 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1378 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1380 glDisable(GL_TEXTURE_3D);
1381 checkGLcall("glDisable GL_TEXTURE_3D");
1382 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1383 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1384 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1386 glDisable(GL_TEXTURE_2D);
1387 checkGLcall("glDisable GL_TEXTURE_2D");
1389 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1391 glMatrixMode(GL_TEXTURE);
1392 checkGLcall("glMatrixMode(GL_TEXTURE)");
1393 glLoadIdentity();
1394 checkGLcall("glLoadIdentity()");
1396 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
1397 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1398 GL_TEXTURE_LOD_BIAS_EXT,
1399 0.0f);
1400 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1403 if (sampler != -1) {
1404 if (sampler < MAX_TEXTURES) {
1405 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1406 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1408 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1411 /* Other misc states */
1412 glDisable(GL_ALPHA_TEST);
1413 checkGLcall("glDisable(GL_ALPHA_TEST)");
1414 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1415 glDisable(GL_LIGHTING);
1416 checkGLcall("glDisable GL_LIGHTING");
1417 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1418 glDisable(GL_DEPTH_TEST);
1419 checkGLcall("glDisable GL_DEPTH_TEST");
1420 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1421 glDisableWINE(GL_FOG);
1422 checkGLcall("glDisable GL_FOG");
1423 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1424 glDisable(GL_BLEND);
1425 checkGLcall("glDisable GL_BLEND");
1426 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1427 glDisable(GL_CULL_FACE);
1428 checkGLcall("glDisable GL_CULL_FACE");
1429 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1430 glDisable(GL_STENCIL_TEST);
1431 checkGLcall("glDisable GL_STENCIL_TEST");
1432 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1433 glDisable(GL_SCISSOR_TEST);
1434 checkGLcall("glDisable GL_SCISSOR_TEST");
1435 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1436 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
1437 glDisable(GL_POINT_SPRITE_ARB);
1438 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1439 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1441 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1442 checkGLcall("glColorMask");
1443 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1444 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
1445 glDisable(GL_COLOR_SUM_EXT);
1446 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1447 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1450 /* Setup transforms */
1451 glMatrixMode(GL_MODELVIEW);
1452 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1453 glLoadIdentity();
1454 checkGLcall("glLoadIdentity()");
1455 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1457 context->last_was_rhw = TRUE;
1458 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1460 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1461 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1462 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1463 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1464 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1465 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1466 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1468 set_blit_dimension(width, height);
1470 LEAVE_GL();
1472 context->blit_w = width; context->blit_h = height;
1473 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1474 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1477 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1480 /*****************************************************************************
1481 * findThreadContextForSwapChain
1483 * Searches a swapchain for all contexts and picks one for the thread tid.
1484 * If none can be found the swapchain is requested to create a new context
1486 *****************************************************************************/
1487 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
1488 unsigned int i;
1490 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1491 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1492 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1497 /* Create a new context for the thread */
1498 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
1501 /*****************************************************************************
1502 * FindContext
1504 * Finds a context for the current render target and thread
1506 * Parameters:
1507 * target: Render target to find the context for
1508 * tid: Thread to activate the context for
1510 * Returns: The needed context
1512 *****************************************************************************/
1513 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
1514 IWineD3DSwapChain *swapchain = NULL;
1515 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
1516 WineD3DContext *context = This->activeContext;
1517 BOOL oldRenderOffscreen = This->render_offscreen;
1518 const struct GlPixelFormatDesc *old = ((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->resource.format_desc;
1519 const struct GlPixelFormatDesc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
1520 const struct StateEntry *StateTable = This->StateTable;
1522 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1523 * the alpha blend state changes with different render target formats
1525 if (old->format != new->format)
1527 /* Disable blending when the alpha mask has changed and when a format doesn't support blending */
1528 if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
1529 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
1531 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1535 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1536 TRACE("Rendering onscreen\n");
1538 context = findThreadContextForSwapChain(swapchain, tid);
1540 This->render_offscreen = FALSE;
1541 /* The context != This->activeContext will catch a NOP context change. This can occur
1542 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1543 * rendering. No context change is needed in that case
1546 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1547 if(This->pbufferContext && tid == This->pbufferContext->tid) {
1548 This->pbufferContext->tid = 0;
1551 IWineD3DSwapChain_Release(swapchain);
1553 if(oldRenderOffscreen) {
1554 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1555 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1556 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1557 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1558 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1561 } else {
1562 TRACE("Rendering offscreen\n");
1563 This->render_offscreen = TRUE;
1565 switch(wined3d_settings.offscreen_rendering_mode) {
1566 case ORM_FBO:
1567 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1568 if(This->activeContext && tid == This->lastThread) {
1569 context = This->activeContext;
1570 } else {
1571 /* This may happen if the app jumps straight into offscreen rendering
1572 * Start using the context of the primary swapchain. tid == 0 is no problem
1573 * for findThreadContextForSwapChain.
1575 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1576 * is perfect to call.
1578 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1580 break;
1582 case ORM_PBUFFER:
1584 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
1585 if(This->pbufferContext == NULL ||
1586 This->pbufferWidth < targetimpl->currentDesc.Width ||
1587 This->pbufferHeight < targetimpl->currentDesc.Height) {
1588 if(This->pbufferContext) {
1589 DestroyContext(This, This->pbufferContext);
1592 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1593 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1595 This->pbufferContext = CreateContext(This, targetimpl,
1596 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1597 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1598 This->pbufferWidth = targetimpl->currentDesc.Width;
1599 This->pbufferHeight = targetimpl->currentDesc.Height;
1602 if(This->pbufferContext) {
1603 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1604 FIXME("The PBuffr context is only supported for one thread for now!\n");
1606 This->pbufferContext->tid = tid;
1607 context = This->pbufferContext;
1608 break;
1609 } else {
1610 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1611 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1615 case ORM_BACKBUFFER:
1616 /* Stay with the currently active context for back buffer rendering */
1617 if(This->activeContext && tid == This->lastThread) {
1618 context = This->activeContext;
1619 } else {
1620 /* This may happen if the app jumps straight into offscreen rendering
1621 * Start using the context of the primary swapchain. tid == 0 is no problem
1622 * for findThreadContextForSwapChain.
1624 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1625 * is perfect to call.
1627 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1629 break;
1632 if(!oldRenderOffscreen) {
1633 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1634 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1635 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1636 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1637 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1641 /* When switching away from an offscreen render target, and we're not using FBOs,
1642 * we have to read the drawable into the texture. This is done via PreLoad(and
1643 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1644 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1645 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1646 * is read. This leads to these possible situations:
1648 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1649 * Nothing to do, we don't even reach this code in this case...
1651 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1652 * The currently active context is OK for readback. Call PreLoad, and it
1653 * performs the read
1655 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1656 * Nothing to do - the drawable is unchanged
1658 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1659 * This is tricky. We have to get a context with the old drawable from somewhere
1660 * before we can switch to the new context. In this case, PreLoad calls
1661 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1662 * is case (2) then. The old drawable is activated for the new thread, and the
1663 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1664 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1665 * target for the new thread
1667 if (readTexture && This->lastActiveRenderTarget != target) {
1668 BOOL oldInDraw = This->isInDraw;
1670 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1671 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1672 * when using offscreen rendering with multithreading
1674 This->isInDraw = TRUE;
1676 /* Do that before switching the context:
1677 * Read the back buffer of the old drawable into the destination texture
1679 if (((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->texture_name_srgb)
1681 surface_internal_preload(This->lastActiveRenderTarget, SRGB_BOTH);
1682 } else {
1683 surface_internal_preload(This->lastActiveRenderTarget, SRGB_RGB);
1686 /* Assume that the drawable will be modified by some other things now */
1687 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1689 This->isInDraw = oldInDraw;
1692 return context;
1695 /* Context activation is done by the caller. */
1696 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1698 const struct wined3d_gl_info *gl_info = This->activeContext->gl_info;
1699 IWineD3DSwapChain *swapchain;
1701 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain)))
1703 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1704 ENTER_GL();
1705 glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1706 checkGLcall("glDrawBuffers()");
1707 LEAVE_GL();
1709 else
1711 ENTER_GL();
1712 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1714 if (!blit)
1716 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1718 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1719 checkGLcall("glDrawBuffers()");
1721 else
1723 glDrawBuffer(This->draw_buffers[0]);
1724 checkGLcall("glDrawBuffer()");
1726 } else {
1727 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1728 checkGLcall("glDrawBuffer()");
1731 else
1733 glDrawBuffer(This->offscreenBuffer);
1734 checkGLcall("glDrawBuffer()");
1736 LEAVE_GL();
1740 /*****************************************************************************
1741 * ActivateContext
1743 * Finds a rendering context and drawable matching the device and render
1744 * target for the current thread, activates them and puts them into the
1745 * requested state.
1747 * Params:
1748 * This: Device to activate the context for
1749 * target: Requested render target
1750 * usage: Prepares the context for blitting, drawing or other actions
1752 *****************************************************************************/
1753 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1754 DWORD tid = GetCurrentThreadId();
1755 DWORD i, dirtyState, idx;
1756 BYTE shift;
1757 WineD3DContext *context;
1758 const struct StateEntry *StateTable = This->StateTable;
1759 const struct wined3d_gl_info *gl_info;
1761 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1762 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1763 context = FindContext(This, target, tid);
1764 context->draw_buffer_dirty = TRUE;
1765 This->lastActiveRenderTarget = target;
1766 This->lastThread = tid;
1767 } else {
1768 /* Stick to the old context */
1769 context = This->activeContext;
1772 gl_info = context->gl_info;
1774 /* Activate the opengl context */
1775 if(last_device != This || context != This->activeContext) {
1776 BOOL ret;
1778 /* Prevent an unneeded context switch as those are expensive */
1779 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1780 TRACE("Already using gl context %p\n", context->glCtx);
1782 else {
1783 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1785 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1786 if(ret == FALSE) {
1787 ERR("Failed to activate the new context\n");
1788 } else if(!context->last_was_blit) {
1789 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1790 } else {
1791 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1794 if(This->activeContext->vshader_const_dirty) {
1795 memset(This->activeContext->vshader_const_dirty, 1,
1796 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1798 if(This->activeContext->pshader_const_dirty) {
1799 memset(This->activeContext->pshader_const_dirty, 1,
1800 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1802 This->activeContext = context;
1803 context_set_last_device(This);
1806 switch (usage) {
1807 case CTXUSAGE_CLEAR:
1808 case CTXUSAGE_DRAWPRIM:
1809 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1810 ENTER_GL();
1811 context_apply_fbo_state(context);
1812 LEAVE_GL();
1814 if (context->draw_buffer_dirty) {
1815 apply_draw_buffer(This, target, FALSE);
1816 context->draw_buffer_dirty = FALSE;
1818 break;
1820 case CTXUSAGE_BLIT:
1821 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1822 if (This->render_offscreen) {
1823 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1824 ENTER_GL();
1825 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1826 context_attach_surface_fbo(context, GL_FRAMEBUFFER_EXT, 0, target);
1827 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER_EXT, NULL, FALSE);
1828 LEAVE_GL();
1829 } else {
1830 ENTER_GL();
1831 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, NULL);
1832 LEAVE_GL();
1834 context->draw_buffer_dirty = TRUE;
1836 if (context->draw_buffer_dirty) {
1837 apply_draw_buffer(This, target, TRUE);
1838 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1839 context->draw_buffer_dirty = FALSE;
1842 break;
1844 default:
1845 break;
1848 switch(usage) {
1849 case CTXUSAGE_RESOURCELOAD:
1850 /* This does not require any special states to be set up */
1851 break;
1853 case CTXUSAGE_CLEAR:
1854 if(context->last_was_blit) {
1855 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1858 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1859 * blending when clearing improves the clearing performance incredibly.
1861 ENTER_GL();
1862 glDisable(GL_BLEND);
1863 LEAVE_GL();
1864 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1866 ENTER_GL();
1867 glEnable(GL_SCISSOR_TEST);
1868 checkGLcall("glEnable GL_SCISSOR_TEST");
1869 LEAVE_GL();
1870 context->last_was_blit = FALSE;
1871 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1872 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1873 break;
1875 case CTXUSAGE_DRAWPRIM:
1876 /* This needs all dirty states applied */
1877 if(context->last_was_blit) {
1878 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1881 IWineD3DDeviceImpl_FindTexUnitMap(This);
1883 ENTER_GL();
1884 for(i=0; i < context->numDirtyEntries; i++) {
1885 dirtyState = context->dirtyArray[i];
1886 idx = dirtyState >> 5;
1887 shift = dirtyState & 0x1f;
1888 context->isStateDirty[idx] &= ~(1 << shift);
1889 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1891 LEAVE_GL();
1892 context->numDirtyEntries = 0; /* This makes the whole list clean */
1893 context->last_was_blit = FALSE;
1894 break;
1896 case CTXUSAGE_BLIT:
1897 SetupForBlit(This, context,
1898 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1899 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1900 break;
1902 default:
1903 FIXME("Unexpected context usage requested\n");
1907 WineD3DContext *getActiveContext(void) {
1908 return last_device->activeContext;