Sync to wine64. Adds support for amd64 relays.. not that we use this feature.
[reactos.git] / reactos / dll / directx / wine / wined3d / context.c
1 /*
2 * Context and render target management in wined3d
3 *
4 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
5 *
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.
10 *
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.
15 *
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
19 */
20
21 #include "config.h"
22 #include <stdio.h>
23 #ifdef HAVE_FLOAT_H
24 # include <float.h>
25 #endif
26 #include "wined3d_private.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
29
30 #define GLINFO_LOCATION This->adapter->gl_info
31
32 /* The last used device.
33 *
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
36 */
37 static IWineD3DDeviceImpl *last_device;
38
39 /* FBO helper functions */
40
41 void context_bind_fbo(IWineD3DDevice *iface, GLenum target, GLuint *fbo)
42 {
43 const IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
44
45 if (!*fbo)
46 {
47 GL_EXTCALL(glGenFramebuffersEXT(1, fbo));
48 checkGLcall("glGenFramebuffersEXT()");
49 TRACE("Created FBO %d\n", *fbo);
50 }
51
52 GL_EXTCALL(glBindFramebufferEXT(target, *fbo));
53 checkGLcall("glBindFramebuffer()");
54 }
55
56 static void context_destroy_fbo(IWineD3DDeviceImpl *This, const GLuint *fbo)
57 {
58 int i = 0;
59
60 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, *fbo));
61 checkGLcall("glBindFramebuffer()");
62 for (i = 0; i < GL_LIMITS(buffers); ++i)
63 {
64 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, 0, 0));
65 checkGLcall("glFramebufferTexture2D()");
66 }
67 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
68 checkGLcall("glFramebufferTexture2D()");
69 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
70 checkGLcall("glBindFramebuffer()");
71 GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo));
72 checkGLcall("glDeleteFramebuffers()");
73 }
74
75 static void context_apply_attachment_filter_states(IWineD3DDevice *iface, IWineD3DSurface *surface, BOOL force_preload)
76 {
77 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
78 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
79 IWineD3DBaseTextureImpl *texture_impl;
80 BOOL update_minfilter = FALSE;
81 BOOL update_magfilter = FALSE;
82
83 /* Update base texture states array */
84 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
85 {
86 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
87 || texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
88 {
89 texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
90 texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
91 update_minfilter = TRUE;
92 }
93
94 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
95 {
96 texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
97 update_magfilter = TRUE;
98 }
99
100 if (texture_impl->baseTexture.bindCount)
101 {
102 WARN("Render targets should not be bound to a sampler\n");
103 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(texture_impl->baseTexture.sampler));
104 }
105
106 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
107 }
108
109 if (update_minfilter || update_magfilter || force_preload)
110 {
111 GLenum target, bind_target;
112 GLint old_binding;
113
114 target = surface_impl->glDescription.target;
115 if (target == GL_TEXTURE_2D)
116 {
117 bind_target = GL_TEXTURE_2D;
118 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
119 } else if (target == GL_TEXTURE_RECTANGLE_ARB) {
120 bind_target = GL_TEXTURE_RECTANGLE_ARB;
121 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
122 } else {
123 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
124 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
125 }
126
127 IWineD3DSurface_PreLoad(surface);
128
129 glBindTexture(bind_target, surface_impl->glDescription.textureName);
130 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
131 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
132 glBindTexture(bind_target, old_binding);
133 }
134
135 checkGLcall("apply_attachment_filter_states()");
136 }
137
138 /* TODO: Handle stencil attachments */
139 void context_attach_depth_stencil_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
140 {
141 IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
142
143 TRACE("Attach depth stencil %p\n", depth_stencil);
144
145 if (depth_stencil)
146 {
147 if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
148 {
149 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
150 checkGLcall("glFramebufferRenderbufferEXT()");
151 } else {
152 context_apply_attachment_filter_states((IWineD3DDevice *)This, depth_stencil, TRUE);
153
154 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, depth_stencil_impl->glDescription.target,
155 depth_stencil_impl->glDescription.textureName, depth_stencil_impl->glDescription.level));
156 checkGLcall("glFramebufferTexture2DEXT()");
157 }
158 } else {
159 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
160 checkGLcall("glFramebufferTexture2DEXT()");
161 }
162 }
163
164 void context_attach_surface_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
165 {
166 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
167
168 TRACE("Attach surface %p to %u\n", surface, idx);
169
170 if (surface)
171 {
172 context_apply_attachment_filter_states((IWineD3DDevice *)This, surface, TRUE);
173
174 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, surface_impl->glDescription.target,
175 surface_impl->glDescription.textureName, surface_impl->glDescription.level));
176 checkGLcall("glFramebufferTexture2DEXT()");
177 } else {
178 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, GL_TEXTURE_2D, 0, 0));
179 checkGLcall("glFramebufferTexture2DEXT()");
180 }
181 }
182
183 static void context_check_fbo_status(IWineD3DDevice *iface)
184 {
185 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
186 GLenum status;
187
188 status = GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
189 if (status == GL_FRAMEBUFFER_COMPLETE_EXT)
190 {
191 TRACE("FBO complete\n");
192 } else {
193 IWineD3DSurfaceImpl *attachment;
194 unsigned int i;
195 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
196
197 /* Dump the FBO attachments */
198 for (i = 0; i < GL_LIMITS(buffers); ++i)
199 {
200 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->render_targets[i];
201 if (attachment)
202 {
203 FIXME("\tColor attachment %d: (%p) %s %ux%u\n", i, attachment, debug_d3dformat(attachment->resource.format),
204 attachment->pow2Width, attachment->pow2Height);
205 }
206 }
207 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->depth_stencil;
208 if (attachment)
209 {
210 FIXME("\tDepth attachment: (%p) %s %ux%u\n", attachment, debug_d3dformat(attachment->resource.format),
211 attachment->pow2Width, attachment->pow2Height);
212 }
213 }
214 }
215
216 static struct fbo_entry *context_create_fbo_entry(IWineD3DDevice *iface)
217 {
218 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
219 struct fbo_entry *entry;
220
221 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
222 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
223 memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
224 entry->depth_stencil = This->stencilBufferTarget;
225 entry->attached = FALSE;
226 entry->id = 0;
227
228 return entry;
229 }
230
231 static void context_destroy_fbo_entry(IWineD3DDeviceImpl *This, struct fbo_entry *entry)
232 {
233 if (entry->id)
234 {
235 TRACE("Destroy FBO %d\n", entry->id);
236 context_destroy_fbo(This, &entry->id);
237 }
238 list_remove(&entry->entry);
239 HeapFree(GetProcessHeap(), 0, entry->render_targets);
240 HeapFree(GetProcessHeap(), 0, entry);
241 }
242
243
244 static struct fbo_entry *context_find_fbo_entry(IWineD3DDevice *iface, WineD3DContext *context)
245 {
246 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
247 struct fbo_entry *entry;
248
249 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
250 {
251 if (!memcmp(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets))
252 && entry->depth_stencil == This->stencilBufferTarget)
253 {
254 return entry;
255 }
256 }
257
258 entry = context_create_fbo_entry(iface);
259 list_add_head(&context->fbo_list, &entry->entry);
260 return entry;
261 }
262
263 static void context_apply_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
264 {
265 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
266 unsigned int i;
267
268 context_bind_fbo(iface, GL_FRAMEBUFFER_EXT, &entry->id);
269
270 if (!entry->attached)
271 {
272 /* Apply render targets */
273 for (i = 0; i < GL_LIMITS(buffers); ++i)
274 {
275 IWineD3DSurface *render_target = This->render_targets[i];
276 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, i, render_target);
277 }
278
279 /* Apply depth targets */
280 if (This->stencilBufferTarget) {
281 unsigned int w = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Width;
282 unsigned int h = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Height;
283
284 surface_set_compatible_renderbuffer(This->stencilBufferTarget, w, h);
285 }
286 context_attach_depth_stencil_fbo(This, GL_FRAMEBUFFER_EXT, This->stencilBufferTarget, TRUE);
287
288 entry->attached = TRUE;
289 } else {
290 for (i = 0; i < GL_LIMITS(buffers); ++i)
291 {
292 if (This->render_targets[i])
293 context_apply_attachment_filter_states(iface, This->render_targets[i], FALSE);
294 }
295 if (This->stencilBufferTarget)
296 context_apply_attachment_filter_states(iface, This->stencilBufferTarget, FALSE);
297 }
298
299 for (i = 0; i < GL_LIMITS(buffers); ++i)
300 {
301 if (This->render_targets[i])
302 This->draw_buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
303 else
304 This->draw_buffers[i] = GL_NONE;
305 }
306 }
307
308 static void context_apply_fbo_state(IWineD3DDevice *iface)
309 {
310 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
311 WineD3DContext *context = This->activeContext;
312
313 if (This->render_offscreen)
314 {
315 context->current_fbo = context_find_fbo_entry(iface, context);
316 context_apply_fbo_entry(iface, context->current_fbo);
317 } else {
318 context->current_fbo = NULL;
319 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
320 }
321
322 context_check_fbo_status(iface);
323 }
324
325 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
326 {
327 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
328 UINT i;
329
330 switch(type)
331 {
332 case WINED3DRTYPE_SURFACE:
333 {
334 for (i = 0; i < This->numContexts; ++i)
335 {
336 struct fbo_entry *entry, *entry2;
337
338 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->contexts[i]->fbo_list, struct fbo_entry, entry)
339 {
340 BOOL destroyed = FALSE;
341 UINT j;
342
343 for (j = 0; !destroyed && j < GL_LIMITS(buffers); ++j)
344 {
345 if (entry->render_targets[j] == (IWineD3DSurface *)resource)
346 {
347 context_destroy_fbo_entry(This, entry);
348 destroyed = TRUE;
349 }
350 }
351
352 if (!destroyed && entry->depth_stencil == (IWineD3DSurface *)resource)
353 context_destroy_fbo_entry(This, entry);
354 }
355 }
356
357 break;
358 }
359
360 default:
361 break;
362 }
363 }
364
365 /*****************************************************************************
366 * Context_MarkStateDirty
367 *
368 * Marks a state in a context dirty. Only one context, opposed to
369 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
370 * contexts
371 *
372 * Params:
373 * context: Context to mark the state dirty in
374 * state: State to mark dirty
375 * StateTable: Pointer to the state table in use(for state grouping)
376 *
377 *****************************************************************************/
378 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
379 DWORD rep = StateTable[state].representative;
380 DWORD idx;
381 BYTE shift;
382
383 if(!rep || isStateDirty(context, rep)) return;
384
385 context->dirtyArray[context->numDirtyEntries++] = rep;
386 idx = rep >> 5;
387 shift = rep & 0x1f;
388 context->isStateDirty[idx] |= (1 << shift);
389 }
390
391 /*****************************************************************************
392 * AddContextToArray
393 *
394 * Adds a context to the context array. Helper function for CreateContext
395 *
396 * This method is not called in performance-critical code paths, only when a
397 * new render target or swapchain is created. Thus performance is not an issue
398 * here.
399 *
400 * Params:
401 * This: Device to add the context for
402 * hdc: device context
403 * glCtx: WGL context to add
404 * pbuffer: optional pbuffer used with this context
405 *
406 *****************************************************************************/
407 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
408 WineD3DContext **oldArray = This->contexts;
409 DWORD state;
410
411 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
412 if(This->contexts == NULL) {
413 ERR("Unable to grow the context array\n");
414 This->contexts = oldArray;
415 return NULL;
416 }
417 if(oldArray) {
418 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
419 }
420
421 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
422 if(This->contexts[This->numContexts] == NULL) {
423 ERR("Unable to allocate a new context\n");
424 HeapFree(GetProcessHeap(), 0, This->contexts);
425 This->contexts = oldArray;
426 return NULL;
427 }
428
429 This->contexts[This->numContexts]->hdc = hdc;
430 This->contexts[This->numContexts]->glCtx = glCtx;
431 This->contexts[This->numContexts]->pbuffer = pbuffer;
432 This->contexts[This->numContexts]->win_handle = win_handle;
433 HeapFree(GetProcessHeap(), 0, oldArray);
434
435 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
436 */
437 for(state = 0; state <= STATE_HIGHEST; state++) {
438 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
439 }
440
441 This->numContexts++;
442 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
443 return This->contexts[This->numContexts - 1];
444 }
445
446 /* This function takes care of WineD3D pixel format selection. */
447 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc, WINED3DFORMAT ColorFormat, WINED3DFORMAT DepthStencilFormat, BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
448 {
449 int iPixelFormat=0;
450 unsigned int matchtry;
451 short redBits, greenBits, blueBits, alphaBits, colorBits;
452 short depthBits=0, stencilBits=0;
453
454 struct match_type {
455 BOOL require_aux;
456 BOOL exact_alpha;
457 BOOL exact_color;
458 } matches[] = {
459 /* First, try without alpha match buffers. MacOS supports aux buffers only
460 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
461 * Then try without aux buffers - this is the most common cause for not
462 * finding a pixel format. Also some drivers(the open source ones)
463 * only offer 32 bit ARB pixel formats. First try without an exact alpha
464 * match, then try without an exact alpha and color match.
465 */
466 { TRUE, TRUE, TRUE },
467 { TRUE, FALSE, TRUE },
468 { FALSE, TRUE, TRUE },
469 { FALSE, FALSE, TRUE },
470 { TRUE, FALSE, FALSE },
471 { FALSE, FALSE, FALSE },
472 };
473
474 int i = 0;
475 int nCfgs = This->adapter->nCfgs;
476
477 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
478 debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat), auxBuffers, numSamples, pbuffer, findCompatible);
479
480 if(!getColorBits(ColorFormat, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
481 ERR("Unable to get color bits for format %s (%#x)!\n", debug_d3dformat(ColorFormat), ColorFormat);
482 return 0;
483 }
484
485 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
486 * You are able to add a depth + stencil surface at a later stage when you need it.
487 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
488 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
489 * context, need torecreate shaders, textures and other resources.
490 *
491 * The context manager already takes care of the state problem and for the other tasks code from Reset
492 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
493 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
494 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
495 * issue needs to be fixed. */
496 if(DepthStencilFormat != WINED3DFMT_D24S8)
497 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
498
499 DepthStencilFormat = WINED3DFMT_D24S8;
500
501 if(DepthStencilFormat) {
502 getDepthStencilBits(DepthStencilFormat, &depthBits, &stencilBits);
503 }
504
505 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
506 for(i=0; i<nCfgs; i++) {
507 BOOL exactDepthMatch = TRUE;
508 WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
509
510 /* For now only accept RGBA formats. Perhaps some day we will
511 * allow floating point formats for pbuffers. */
512 if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
513 continue;
514
515 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
516 if(!pbuffer && !(cfg->windowDrawable && cfg->doubleBuffer))
517 continue;
518
519 /* We like to have aux buffers in backbuffer mode */
520 if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
521 continue;
522
523 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
524 if(pbuffer && (!cfg->pbufferDrawable || cfg->doubleBuffer))
525 continue;
526
527 if(matches[matchtry].exact_color) {
528 if(cfg->redSize != redBits)
529 continue;
530 if(cfg->greenSize != greenBits)
531 continue;
532 if(cfg->blueSize != blueBits)
533 continue;
534 } else {
535 if(cfg->redSize < redBits)
536 continue;
537 if(cfg->greenSize < greenBits)
538 continue;
539 if(cfg->blueSize < blueBits)
540 continue;
541 }
542 if(matches[matchtry].exact_alpha) {
543 if(cfg->alphaSize != alphaBits)
544 continue;
545 } else {
546 if(cfg->alphaSize < alphaBits)
547 continue;
548 }
549
550 /* We try to locate a format which matches our requirements exactly. In case of
551 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
552 if(cfg->depthSize < depthBits)
553 continue;
554 else if(cfg->depthSize > depthBits)
555 exactDepthMatch = FALSE;
556
557 /* In all cases make sure the number of stencil bits matches our requirements
558 * even when we don't need stencil because it could affect performance EXCEPT
559 * on cards which don't offer depth formats without stencil like the i915 drivers
560 * on Linux. */
561 if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
562 continue;
563
564 /* Check multisampling support */
565 if(cfg->numSamples != numSamples)
566 continue;
567
568 /* When we have passed all the checks then we have found a format which matches our
569 * requirements. Note that we only check for a limit number of capabilities right now,
570 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
571 * can still differ in things like multisampling, stereo, SRGB and other flags.
572 */
573
574 /* Exit the loop as we have found a format :) */
575 if(exactDepthMatch) {
576 iPixelFormat = cfg->iPixelFormat;
577 break;
578 } else if(!iPixelFormat) {
579 /* In the end we might end up with a format which doesn't exactly match our depth
580 * requirements. Accept the first format we found because formats with higher iPixelFormat
581 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
582 iPixelFormat = cfg->iPixelFormat;
583 }
584 }
585 }
586
587 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
588 if(!iPixelFormat && !findCompatible) {
589 ERR("Can't find a suitable iPixelFormat\n");
590 return FALSE;
591 } else if(!iPixelFormat) {
592 PIXELFORMATDESCRIPTOR pfd;
593
594 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
595 /* PixelFormat selection */
596 ZeroMemory(&pfd, sizeof(pfd));
597 pfd.nSize = sizeof(pfd);
598 pfd.nVersion = 1;
599 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
600 pfd.iPixelType = PFD_TYPE_RGBA;
601 pfd.cAlphaBits = alphaBits;
602 pfd.cColorBits = colorBits;
603 pfd.cDepthBits = depthBits;
604 pfd.cStencilBits = stencilBits;
605 pfd.iLayerType = PFD_MAIN_PLANE;
606
607 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
608 if(!iPixelFormat) {
609 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
610 ERR("Can't find a suitable iPixelFormat\n");
611 return FALSE;
612 }
613 }
614
615 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n", iPixelFormat, debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat));
616 return iPixelFormat;
617 }
618
619 /*****************************************************************************
620 * CreateContext
621 *
622 * Creates a new context for a window, or a pbuffer context.
623 *
624 * * Params:
625 * This: Device to activate the context for
626 * target: Surface this context will render to
627 * win_handle: handle to the window which we are drawing to
628 * create_pbuffer: tells whether to create a pbuffer or not
629 * pPresentParameters: contains the pixelformats to use for onscreen rendering
630 *
631 *****************************************************************************/
632 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
633 HDC oldDrawable, hdc;
634 HPBUFFERARB pbuffer = NULL;
635 HGLRC ctx = NULL, oldCtx;
636 WineD3DContext *ret = NULL;
637 int s;
638
639 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
640
641 if(create_pbuffer) {
642 HDC hdc_parent = GetDC(win_handle);
643 int iPixelFormat = 0;
644
645 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
646 WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
647
648 /* Try to find a pixel format with pbuffer support. */
649 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */, FALSE /* findCompatible */);
650 if(!iPixelFormat) {
651 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
652
653 /* For some reason we weren't able to find a format, try to find something instead of crashing.
654 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
655 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */, TRUE /* findCompatible */);
656 }
657
658 /* This shouldn't happen as ChoosePixelFormat always returns something */
659 if(!iPixelFormat) {
660 ERR("Unable to locate a pixel format for a pbuffer\n");
661 ReleaseDC(win_handle, hdc_parent);
662 goto out;
663 }
664
665 TRACE("Creating a pBuffer drawable for the new context\n");
666 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
667 if(!pbuffer) {
668 ERR("Cannot create a pbuffer\n");
669 ReleaseDC(win_handle, hdc_parent);
670 goto out;
671 }
672
673 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
674 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
675 if(!hdc) {
676 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
677 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
678 ReleaseDC(win_handle, hdc_parent);
679 goto out;
680 }
681 ReleaseDC(win_handle, hdc_parent);
682 } else {
683 PIXELFORMATDESCRIPTOR pfd;
684 int iPixelFormat;
685 int res;
686 WINED3DFORMAT ColorFormat = target->resource.format;
687 WINED3DFORMAT DepthStencilFormat = 0;
688 BOOL auxBuffers = FALSE;
689 int numSamples = 0;
690
691 hdc = GetDC(win_handle);
692 if(hdc == NULL) {
693 ERR("Cannot retrieve a device context!\n");
694 goto out;
695 }
696
697 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
698 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
699 auxBuffers = TRUE;
700
701 if(target->resource.format == WINED3DFMT_X4R4G4B4)
702 ColorFormat = WINED3DFMT_A4R4G4B4;
703 else if(target->resource.format == WINED3DFMT_X8R8G8B8)
704 ColorFormat = WINED3DFMT_A8R8G8B8;
705 }
706
707 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
708 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
709 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
710 * a format with 8bit alpha, so request A8R8G8B8. */
711 if(ColorFormat == WINED3DFMT_P8)
712 ColorFormat = WINED3DFMT_A8R8G8B8;
713
714 /* Retrieve the depth stencil format from the present parameters.
715 * The choice of the proper format can give a nice performance boost
716 * in case of GPU limited programs. */
717 if(pPresentParms->EnableAutoDepthStencil) {
718 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
719 DepthStencilFormat = pPresentParms->AutoDepthStencilFormat;
720 }
721
722 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
723 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
724 if(!GL_SUPPORT(ARB_MULTISAMPLE))
725 ERR("The program is requesting multisampling without support!\n");
726 else {
727 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
728 numSamples = pPresentParms->MultiSampleType;
729 }
730 }
731
732 /* Try to find a pixel format which matches our requirements */
733 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
734
735 /* Try to locate a compatible format if we weren't able to find anything */
736 if(!iPixelFormat) {
737 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
738 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
739 }
740
741 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
742 if(!iPixelFormat) {
743 ERR("Can't find a suitable iPixelFormat\n");
744 return FALSE;
745 }
746
747 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
748 res = SetPixelFormat(hdc, iPixelFormat, NULL);
749 if(!res) {
750 int oldPixelFormat = GetPixelFormat(hdc);
751
752 /* By default WGL doesn't allow pixel format adjustments but we need it here.
753 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
754 * set the pixel format multiple times. Only use it when it is really needed. */
755
756 if(oldPixelFormat == iPixelFormat) {
757 /* We don't have to do anything as the formats are the same :) */
758 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
759 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
760
761 if(!res) {
762 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
763 return FALSE;
764 }
765 } else if(oldPixelFormat) {
766 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
767 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
768 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
769 } else {
770 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
771 return FALSE;
772 }
773 }
774 }
775
776 ctx = pwglCreateContext(hdc);
777 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
778
779 if(!ctx) {
780 ERR("Failed to create a WGL context\n");
781 if(create_pbuffer) {
782 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
783 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
784 }
785 goto out;
786 }
787 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
788 if(!ret) {
789 ERR("Failed to add the newly created context to the context list\n");
790 pwglDeleteContext(ctx);
791 if(create_pbuffer) {
792 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
793 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
794 }
795 goto out;
796 }
797 ret->surface = (IWineD3DSurface *) target;
798 ret->isPBuffer = create_pbuffer;
799 ret->tid = GetCurrentThreadId();
800 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
801 /* Create the dirty constants array and initialize them to dirty */
802 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
803 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
804 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
805 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
806 memset(ret->vshader_const_dirty, 1,
807 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
808 memset(ret->pshader_const_dirty, 1,
809 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
810 }
811
812 TRACE("Successfully created new context %p\n", ret);
813
814 list_init(&ret->fbo_list);
815
816 /* Set up the context defaults */
817 oldCtx = pwglGetCurrentContext();
818 oldDrawable = pwglGetCurrentDC();
819 if(oldCtx && oldDrawable) {
820 /* See comment in ActivateContext context switching */
821 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
822 }
823 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
824 ERR("Cannot activate context to set up defaults\n");
825 goto out;
826 }
827
828 ENTER_GL();
829
830 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
831
832 TRACE("Setting up the screen\n");
833 /* Clear the screen */
834 glClearColor(1.0, 0.0, 0.0, 0.0);
835 checkGLcall("glClearColor");
836 glClearIndex(0);
837 glClearDepth(1);
838 glClearStencil(0xffff);
839
840 checkGLcall("glClear");
841
842 glColor3f(1.0, 1.0, 1.0);
843 checkGLcall("glColor3f");
844
845 glEnable(GL_LIGHTING);
846 checkGLcall("glEnable");
847
848 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
849 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
850
851 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
852 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
853
854 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
855 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
856
857 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
858 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
859 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
860 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
861
862 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
863 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
864 * and textures in DIB sections(due to the memory protection).
865 */
866 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
867 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
868 }
869 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
870 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
871 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
872 * GL_VERTEX_BLEND_ARB isn't enabled too
873 */
874 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
875 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
876 }
877 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
878 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
879 * the previous texture where to source the offset from is always unit - 1.
880 */
881 for(s = 1; s < GL_LIMITS(textures); s++) {
882 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
883 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
884 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
885 }
886 }
887
888 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
889 for(s = 0; s < GL_LIMITS(textures); s++) {
890 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
891 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
892 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
893 }
894 }
895 LEAVE_GL();
896
897 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
898 * but enable it for the first context we create, and reenable it on the old context
899 */
900 if(oldDrawable && oldCtx) {
901 pwglMakeCurrent(oldDrawable, oldCtx);
902 } else {
903 last_device = This;
904 }
905 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
906
907 return ret;
908
909 out:
910 return NULL;
911 }
912
913 /*****************************************************************************
914 * RemoveContextFromArray
915 *
916 * Removes a context from the context manager. The opengl context is not
917 * destroyed or unset. context is not a valid pointer after that call.
918 *
919 * Similar to the former call this isn't a performance critical function. A
920 * helper function for DestroyContext.
921 *
922 * Params:
923 * This: Device to activate the context for
924 * context: Context to remove
925 *
926 *****************************************************************************/
927 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
928 UINT t, s;
929 WineD3DContext **oldArray = This->contexts;
930
931 TRACE("Removing ctx %p\n", context);
932
933 This->numContexts--;
934
935 if(This->numContexts) {
936 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
937 if(!This->contexts) {
938 ERR("Cannot allocate a new context array, PANIC!!!\n");
939 }
940 t = 0;
941 /* Note that we decreased numContexts a few lines up, so use '<=' instead of '<' */
942 for(s = 0; s <= This->numContexts; s++) {
943 if(oldArray[s] == context) continue;
944 This->contexts[t] = oldArray[s];
945 t++;
946 }
947 } else {
948 This->contexts = NULL;
949 }
950
951 HeapFree(GetProcessHeap(), 0, context);
952 HeapFree(GetProcessHeap(), 0, oldArray);
953 }
954
955 /*****************************************************************************
956 * DestroyContext
957 *
958 * Destroys a wineD3DContext
959 *
960 * Params:
961 * This: Device to activate the context for
962 * context: Context to destroy
963 *
964 *****************************************************************************/
965 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
966 struct fbo_entry *entry, *entry2;
967
968 TRACE("Destroying ctx %p\n", context);
969
970 /* The correct GL context needs to be active to cleanup the GL resources below */
971 if(pwglGetCurrentContext() != context->glCtx){
972 pwglMakeCurrent(context->hdc, context->glCtx);
973 last_device = NULL;
974 }
975
976 ENTER_GL();
977
978 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
979 context_destroy_fbo_entry(This, entry);
980 }
981 if (context->src_fbo) {
982 TRACE("Destroy src FBO %d\n", context->src_fbo);
983 context_destroy_fbo(This, &context->src_fbo);
984 }
985 if (context->dst_fbo) {
986 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
987 context_destroy_fbo(This, &context->dst_fbo);
988 }
989
990 LEAVE_GL();
991
992 /* Cleanup the GL context */
993 pwglMakeCurrent(NULL, NULL);
994 if(context->isPBuffer) {
995 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
996 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
997 } else ReleaseDC(context->win_handle, context->hdc);
998 pwglDeleteContext(context->glCtx);
999
1000 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1001 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1002 RemoveContextFromArray(This, context);
1003 }
1004
1005 static inline void set_blit_dimension(UINT width, UINT height) {
1006 glMatrixMode(GL_PROJECTION);
1007 checkGLcall("glMatrixMode(GL_PROJECTION)");
1008 glLoadIdentity();
1009 checkGLcall("glLoadIdentity()");
1010 glOrtho(0, width, height, 0, 0.0, -1.0);
1011 checkGLcall("glOrtho");
1012 glViewport(0, 0, width, height);
1013 checkGLcall("glViewport");
1014 }
1015
1016 /*****************************************************************************
1017 * SetupForBlit
1018 *
1019 * Sets up a context for DirectDraw blitting.
1020 * All texture units are disabled, texture unit 0 is set as current unit
1021 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1022 * color writing enabled for all channels
1023 * register combiners disabled, shaders disabled
1024 * world matrix is set to identity, texture matrix 0 too
1025 * projection matrix is setup for drawing screen coordinates
1026 *
1027 * Params:
1028 * This: Device to activate the context for
1029 * context: Context to setup
1030 * width: render target width
1031 * height: render target height
1032 *
1033 *****************************************************************************/
1034 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
1035 int i, sampler;
1036 const struct StateEntry *StateTable = This->StateTable;
1037
1038 TRACE("Setting up context %p for blitting\n", context);
1039 if(context->last_was_blit) {
1040 if(context->blit_w != width || context->blit_h != height) {
1041 set_blit_dimension(width, height);
1042 context->blit_w = width; context->blit_h = height;
1043 /* No need to dirtify here, the states are still dirtified because they weren't
1044 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1045 * be set
1046 */
1047 }
1048 TRACE("Context is already set up for blitting, nothing to do\n");
1049 return;
1050 }
1051 context->last_was_blit = TRUE;
1052
1053 /* TODO: Use a display list */
1054
1055 /* Disable shaders */
1056 This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
1057 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1058 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1059
1060 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1061 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1062 * which can safely be called from here, we only lock once instead locking/unlocking
1063 * after each GL call.
1064 */
1065 ENTER_GL();
1066
1067 /* Disable all textures. The caller can then bind a texture it wants to blit
1068 * from
1069 */
1070 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
1071 /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1072 * function texture unit. No need to care for higher samplers
1073 */
1074 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
1075 sampler = This->rev_tex_unit_map[i];
1076 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1077 checkGLcall("glActiveTextureARB");
1078
1079 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1080 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1081 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1082 }
1083 glDisable(GL_TEXTURE_3D);
1084 checkGLcall("glDisable GL_TEXTURE_3D");
1085 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1086 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1087 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1088 }
1089 glDisable(GL_TEXTURE_2D);
1090 checkGLcall("glDisable GL_TEXTURE_2D");
1091
1092 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1093 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1094
1095 if (sampler != -1) {
1096 if (sampler < MAX_TEXTURES) {
1097 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1098 }
1099 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1100 }
1101 }
1102 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1103 checkGLcall("glActiveTextureARB");
1104 }
1105
1106 sampler = This->rev_tex_unit_map[0];
1107
1108 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1109 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1110 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1111 }
1112 glDisable(GL_TEXTURE_3D);
1113 checkGLcall("glDisable GL_TEXTURE_3D");
1114 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1115 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1116 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1117 }
1118 glDisable(GL_TEXTURE_2D);
1119 checkGLcall("glDisable GL_TEXTURE_2D");
1120
1121 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1122
1123 glMatrixMode(GL_TEXTURE);
1124 checkGLcall("glMatrixMode(GL_TEXTURE)");
1125 glLoadIdentity();
1126 checkGLcall("glLoadIdentity()");
1127
1128 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
1129 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1130 GL_TEXTURE_LOD_BIAS_EXT,
1131 0.0);
1132 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1133 }
1134
1135 if (sampler != -1) {
1136 if (sampler < MAX_TEXTURES) {
1137 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1138 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1139 }
1140 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1141 }
1142
1143 /* Other misc states */
1144 glDisable(GL_ALPHA_TEST);
1145 checkGLcall("glDisable(GL_ALPHA_TEST)");
1146 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1147 glDisable(GL_LIGHTING);
1148 checkGLcall("glDisable GL_LIGHTING");
1149 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1150 glDisable(GL_DEPTH_TEST);
1151 checkGLcall("glDisable GL_DEPTH_TEST");
1152 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1153 glDisable(GL_FOG);
1154 checkGLcall("glDisable GL_FOG");
1155 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1156 glDisable(GL_BLEND);
1157 checkGLcall("glDisable GL_BLEND");
1158 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1159 glDisable(GL_CULL_FACE);
1160 checkGLcall("glDisable GL_CULL_FACE");
1161 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1162 glDisable(GL_STENCIL_TEST);
1163 checkGLcall("glDisable GL_STENCIL_TEST");
1164 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1165 glDisable(GL_SCISSOR_TEST);
1166 checkGLcall("glDisable GL_SCISSOR_TEST");
1167 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1168 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
1169 glDisable(GL_POINT_SPRITE_ARB);
1170 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1171 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1172 }
1173 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1174 checkGLcall("glColorMask");
1175 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1176 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
1177 glDisable(GL_COLOR_SUM_EXT);
1178 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1179 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1180 }
1181
1182 /* Setup transforms */
1183 glMatrixMode(GL_MODELVIEW);
1184 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1185 glLoadIdentity();
1186 checkGLcall("glLoadIdentity()");
1187 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1188
1189 context->last_was_rhw = TRUE;
1190 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1191
1192 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1193 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1194 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1195 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1196 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1197 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1198 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1199 LEAVE_GL();
1200
1201 set_blit_dimension(width, height);
1202 context->blit_w = width; context->blit_h = height;
1203 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1204 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1205
1206
1207 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1208 }
1209
1210 /*****************************************************************************
1211 * findThreadContextForSwapChain
1212 *
1213 * Searches a swapchain for all contexts and picks one for the thread tid.
1214 * If none can be found the swapchain is requested to create a new context
1215 *
1216 *****************************************************************************/
1217 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
1218 unsigned int i;
1219
1220 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1221 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1222 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1223 }
1224
1225 }
1226
1227 /* Create a new context for the thread */
1228 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
1229 }
1230
1231 /*****************************************************************************
1232 * FindContext
1233 *
1234 * Finds a context for the current render target and thread
1235 *
1236 * Parameters:
1237 * target: Render target to find the context for
1238 * tid: Thread to activate the context for
1239 *
1240 * Returns: The needed context
1241 *
1242 *****************************************************************************/
1243 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
1244 IWineD3DSwapChain *swapchain = NULL;
1245 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
1246 WineD3DContext *context = This->activeContext;
1247 BOOL oldRenderOffscreen = This->render_offscreen;
1248 const WINED3DFORMAT oldFmt = ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->resource.format;
1249 const WINED3DFORMAT newFmt = ((IWineD3DSurfaceImpl *) target)->resource.format;
1250 const struct StateEntry *StateTable = This->StateTable;
1251
1252 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1253 * the alpha blend state changes with different render target formats
1254 */
1255 if(oldFmt != newFmt) {
1256 const GlPixelFormatDesc *glDesc;
1257 const StaticPixelFormatDesc *old = getFormatDescEntry(oldFmt, NULL, NULL);
1258 const StaticPixelFormatDesc *new = getFormatDescEntry(newFmt, &GLINFO_LOCATION, &glDesc);
1259
1260 /* Disable blending when the alphaMask has changed and when a format doesn't support blending */
1261 if((old->alphaMask && !new->alphaMask) || (!old->alphaMask && new->alphaMask) || !(glDesc->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING)) {
1262 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1263 }
1264 }
1265
1266 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1267 TRACE("Rendering onscreen\n");
1268
1269 context = findThreadContextForSwapChain(swapchain, tid);
1270
1271 This->render_offscreen = FALSE;
1272 /* The context != This->activeContext will catch a NOP context change. This can occur
1273 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1274 * rendering. No context change is needed in that case
1275 */
1276
1277 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1278 if(This->pbufferContext && tid == This->pbufferContext->tid) {
1279 This->pbufferContext->tid = 0;
1280 }
1281 }
1282 IWineD3DSwapChain_Release(swapchain);
1283
1284 if(oldRenderOffscreen) {
1285 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1286 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1287 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1288 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1289 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1290 }
1291
1292 } else {
1293 TRACE("Rendering offscreen\n");
1294 This->render_offscreen = TRUE;
1295
1296 switch(wined3d_settings.offscreen_rendering_mode) {
1297 case ORM_FBO:
1298 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1299 if(This->activeContext && tid == This->lastThread) {
1300 context = This->activeContext;
1301 } else {
1302 /* This may happen if the app jumps straight into offscreen rendering
1303 * Start using the context of the primary swapchain. tid == 0 is no problem
1304 * for findThreadContextForSwapChain.
1305 *
1306 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1307 * is perfect to call.
1308 */
1309 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1310 }
1311 break;
1312
1313 case ORM_PBUFFER:
1314 {
1315 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
1316 if(This->pbufferContext == NULL ||
1317 This->pbufferWidth < targetimpl->currentDesc.Width ||
1318 This->pbufferHeight < targetimpl->currentDesc.Height) {
1319 if(This->pbufferContext) {
1320 DestroyContext(This, This->pbufferContext);
1321 }
1322
1323 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1324 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1325 */
1326 This->pbufferContext = CreateContext(This, targetimpl,
1327 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1328 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1329 This->pbufferWidth = targetimpl->currentDesc.Width;
1330 This->pbufferHeight = targetimpl->currentDesc.Height;
1331 }
1332
1333 if(This->pbufferContext) {
1334 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1335 FIXME("The PBuffr context is only supported for one thread for now!\n");
1336 }
1337 This->pbufferContext->tid = tid;
1338 context = This->pbufferContext;
1339 break;
1340 } else {
1341 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1342 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1343 }
1344 }
1345
1346 case ORM_BACKBUFFER:
1347 /* Stay with the currently active context for back buffer rendering */
1348 if(This->activeContext && tid == This->lastThread) {
1349 context = This->activeContext;
1350 } else {
1351 /* This may happen if the app jumps straight into offscreen rendering
1352 * Start using the context of the primary swapchain. tid == 0 is no problem
1353 * for findThreadContextForSwapChain.
1354 *
1355 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1356 * is perfect to call.
1357 */
1358 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1359 }
1360 break;
1361 }
1362
1363 if(!oldRenderOffscreen) {
1364 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1365 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1366 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1367 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1368 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1369 }
1370 }
1371
1372 /* When switching away from an offscreen render target, and we're not using FBOs,
1373 * we have to read the drawable into the texture. This is done via PreLoad(and
1374 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1375 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1376 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1377 * is read. This leads to these possible situations:
1378 *
1379 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1380 * Nothing to do, we don't even reach this code in this case...
1381 *
1382 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1383 * The currently active context is OK for readback. Call PreLoad, and it
1384 * performs the read
1385 *
1386 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1387 * Nothing to do - the drawable is unchanged
1388 *
1389 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1390 * This is tricky. We have to get a context with the old drawable from somewhere
1391 * before we can switch to the new context. In this case, PreLoad calls
1392 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1393 * is case (2) then. The old drawable is activated for the new thread, and the
1394 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1395 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1396 * target for the new thread
1397 */
1398 if (readTexture && This->lastActiveRenderTarget != target) {
1399 BOOL oldInDraw = This->isInDraw;
1400
1401 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1402 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1403 * when using offscreen rendering with multithreading
1404 */
1405 This->isInDraw = TRUE;
1406
1407 /* Do that before switching the context:
1408 * Read the back buffer of the old drawable into the destination texture
1409 */
1410 IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
1411
1412 /* Assume that the drawable will be modified by some other things now */
1413 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1414
1415 This->isInDraw = oldInDraw;
1416 }
1417
1418 return context;
1419 }
1420
1421 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1422 {
1423 IWineD3DSwapChain *swapchain;
1424
1425 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain)))
1426 {
1427 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1428 ENTER_GL();
1429 glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1430 checkGLcall("glDrawBuffers()");
1431 LEAVE_GL();
1432 }
1433 else
1434 {
1435 ENTER_GL();
1436 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1437 {
1438 if (!blit)
1439 {
1440 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1441 {
1442 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1443 checkGLcall("glDrawBuffers()");
1444 }
1445 else
1446 {
1447 glDrawBuffer(This->draw_buffers[0]);
1448 checkGLcall("glDrawBuffer()");
1449 }
1450 } else {
1451 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1452 checkGLcall("glDrawBuffer()");
1453 }
1454 }
1455 else
1456 {
1457 glDrawBuffer(This->offscreenBuffer);
1458 checkGLcall("glDrawBuffer()");
1459 }
1460 LEAVE_GL();
1461 }
1462 }
1463
1464 /*****************************************************************************
1465 * ActivateContext
1466 *
1467 * Finds a rendering context and drawable matching the device and render
1468 * target for the current thread, activates them and puts them into the
1469 * requested state.
1470 *
1471 * Params:
1472 * This: Device to activate the context for
1473 * target: Requested render target
1474 * usage: Prepares the context for blitting, drawing or other actions
1475 *
1476 *****************************************************************************/
1477 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1478 DWORD tid = GetCurrentThreadId();
1479 DWORD i, dirtyState, idx;
1480 BYTE shift;
1481 WineD3DContext *context;
1482 const struct StateEntry *StateTable = This->StateTable;
1483
1484 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1485 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1486 context = FindContext(This, target, tid);
1487 context->draw_buffer_dirty = TRUE;
1488 This->lastActiveRenderTarget = target;
1489 This->lastThread = tid;
1490 } else {
1491 /* Stick to the old context */
1492 context = This->activeContext;
1493 }
1494
1495 /* Activate the opengl context */
1496 if(last_device != This || context != This->activeContext) {
1497 BOOL ret;
1498
1499 /* Prevent an unneeded context switch as those are expensive */
1500 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1501 TRACE("Already using gl context %p\n", context->glCtx);
1502 }
1503 else {
1504 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1505
1506 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1507 if(ret == FALSE) {
1508 ERR("Failed to activate the new context\n");
1509 } else if(!context->last_was_blit) {
1510 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1511 } else {
1512 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1513 }
1514 }
1515 if(This->activeContext->vshader_const_dirty) {
1516 memset(This->activeContext->vshader_const_dirty, 1,
1517 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1518 }
1519 if(This->activeContext->pshader_const_dirty) {
1520 memset(This->activeContext->pshader_const_dirty, 1,
1521 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1522 }
1523 This->activeContext = context;
1524 last_device = This;
1525 }
1526
1527 switch (usage) {
1528 case CTXUSAGE_CLEAR:
1529 case CTXUSAGE_DRAWPRIM:
1530 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1531 context_apply_fbo_state((IWineD3DDevice *)This);
1532 }
1533 if (context->draw_buffer_dirty) {
1534 apply_draw_buffer(This, target, FALSE);
1535 context->draw_buffer_dirty = FALSE;
1536 }
1537 break;
1538
1539 case CTXUSAGE_BLIT:
1540 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1541 if (This->render_offscreen) {
1542 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1543 context_bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1544 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1545
1546 ENTER_GL();
1547 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0));
1548 checkGLcall("glFramebufferRenderbufferEXT");
1549 LEAVE_GL();
1550 } else {
1551 ENTER_GL();
1552 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1553 checkGLcall("glFramebufferRenderbufferEXT");
1554 LEAVE_GL();
1555 }
1556 context->draw_buffer_dirty = TRUE;
1557 }
1558 if (context->draw_buffer_dirty) {
1559 apply_draw_buffer(This, target, TRUE);
1560 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1561 context->draw_buffer_dirty = FALSE;
1562 }
1563 }
1564 break;
1565
1566 default:
1567 break;
1568 }
1569
1570 switch(usage) {
1571 case CTXUSAGE_RESOURCELOAD:
1572 /* This does not require any special states to be set up */
1573 break;
1574
1575 case CTXUSAGE_CLEAR:
1576 if(context->last_was_blit) {
1577 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1578 }
1579
1580 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1581 * blending when clearing improves the clearing performance incredibly.
1582 */
1583 ENTER_GL();
1584 glDisable(GL_BLEND);
1585 LEAVE_GL();
1586 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1587
1588 ENTER_GL();
1589 glEnable(GL_SCISSOR_TEST);
1590 checkGLcall("glEnable GL_SCISSOR_TEST");
1591 LEAVE_GL();
1592 context->last_was_blit = FALSE;
1593 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1594 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1595 break;
1596
1597 case CTXUSAGE_DRAWPRIM:
1598 /* This needs all dirty states applied */
1599 if(context->last_was_blit) {
1600 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1601 }
1602
1603 IWineD3DDeviceImpl_FindTexUnitMap(This);
1604
1605 for(i=0; i < context->numDirtyEntries; i++) {
1606 dirtyState = context->dirtyArray[i];
1607 idx = dirtyState >> 5;
1608 shift = dirtyState & 0x1f;
1609 context->isStateDirty[idx] &= ~(1 << shift);
1610 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1611 }
1612 context->numDirtyEntries = 0; /* This makes the whole list clean */
1613 context->last_was_blit = FALSE;
1614 break;
1615
1616 case CTXUSAGE_BLIT:
1617 SetupForBlit(This, context,
1618 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1619 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1620 break;
1621
1622 default:
1623 FIXME("Unexpected context usage requested\n");
1624 }
1625 }