wined3d: Remove IWineD3DSurface::PrivateSetup() from the public interface.
[wine] / dlls / wined3d / swapchain.c
1 /*
2  * Copyright 2002-2003 Jason Edmeades
3  * Copyright 2002-2003 Raphael Junqueira
4  * Copyright 2005 Oliver Stieber
5  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
6  * Copyright 2011 Henri Verbeet for CodeWeavers
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wined3d_private.h"
25
26 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
27 WINE_DECLARE_DEBUG_CHANNEL(fps);
28
29 /* Do not call while under the GL lock. */
30 static void swapchain_cleanup(struct wined3d_swapchain *swapchain)
31 {
32     WINED3DDISPLAYMODE mode;
33     UINT i;
34
35     TRACE("Destroying swapchain %p.\n", swapchain);
36
37     wined3d_swapchain_set_gamma_ramp(swapchain, 0, &swapchain->orig_gamma);
38
39     /* Release the swapchain's draw buffers. Make sure swapchain->back_buffers[0]
40      * is the last buffer to be destroyed, FindContext() depends on that. */
41     if (swapchain->front_buffer)
42     {
43         surface_set_container(swapchain->front_buffer, WINED3D_CONTAINER_NONE, NULL);
44         if (IWineD3DSurface_Release((IWineD3DSurface *)swapchain->front_buffer))
45             WARN("Something's still holding the front buffer (%p).\n", swapchain->front_buffer);
46         swapchain->front_buffer = NULL;
47     }
48
49     if (swapchain->back_buffers)
50     {
51         i = swapchain->presentParms.BackBufferCount;
52
53         while (i--)
54         {
55             surface_set_container(swapchain->back_buffers[i], WINED3D_CONTAINER_NONE, NULL);
56             if (IWineD3DSurface_Release((IWineD3DSurface *)swapchain->back_buffers[i]))
57                 WARN("Something's still holding back buffer %u (%p).\n", i, swapchain->back_buffers[i]);
58         }
59         HeapFree(GetProcessHeap(), 0, swapchain->back_buffers);
60         swapchain->back_buffers = NULL;
61     }
62
63     for (i = 0; i < swapchain->num_contexts; ++i)
64     {
65         context_destroy(swapchain->device, swapchain->context[i]);
66     }
67     HeapFree(GetProcessHeap(), 0, swapchain->context);
68
69     /* Restore the screen resolution if we rendered in fullscreen.
70      * This will restore the screen resolution to what it was before creating
71      * the swapchain. In case of d3d8 and d3d9 this will be the original
72      * desktop resolution. In case of d3d7 this will be a NOP because ddraw
73      * sets the resolution before starting up Direct3D, thus orig_width and
74      * orig_height will be equal to the modes in the presentation params. */
75     if (!swapchain->presentParms.Windowed && swapchain->presentParms.AutoRestoreDisplayMode)
76     {
77         mode.Width = swapchain->orig_width;
78         mode.Height = swapchain->orig_height;
79         mode.RefreshRate = 0;
80         mode.Format = swapchain->orig_fmt;
81         IWineD3DDevice_SetDisplayMode((IWineD3DDevice *)swapchain->device, 0, &mode);
82     }
83
84     if (swapchain->backup_dc)
85     {
86         TRACE("Destroying backup wined3d window %p, dc %p.\n", swapchain->backup_wnd, swapchain->backup_dc);
87
88         ReleaseDC(swapchain->backup_wnd, swapchain->backup_dc);
89         DestroyWindow(swapchain->backup_wnd);
90     }
91 }
92
93 ULONG CDECL wined3d_swapchain_incref(struct wined3d_swapchain *swapchain)
94 {
95     ULONG refcount = InterlockedIncrement(&swapchain->ref);
96
97     TRACE("%p increasing refcount to %u.\n", swapchain, refcount);
98
99     return refcount;
100 }
101
102 /* Do not call while under the GL lock. */
103 ULONG CDECL wined3d_swapchain_decref(struct wined3d_swapchain *swapchain)
104 {
105     ULONG refcount = InterlockedDecrement(&swapchain->ref);
106
107     TRACE("%p decreasing refcount to %u.\n", swapchain, refcount);
108
109     if (!refcount)
110     {
111         swapchain_cleanup(swapchain);
112         swapchain->parent_ops->wined3d_object_destroyed(swapchain->parent);
113         HeapFree(GetProcessHeap(), 0, swapchain);
114     }
115
116     return refcount;
117 }
118
119 void * CDECL wined3d_swapchain_get_parent(const struct wined3d_swapchain *swapchain)
120 {
121     TRACE("swapchain %p.\n", swapchain);
122
123     return swapchain->parent;
124 }
125
126 HRESULT CDECL wined3d_swapchain_set_window(struct wined3d_swapchain *swapchain, HWND window)
127 {
128     if (!window)
129         window = swapchain->device_window;
130     if (window == swapchain->win_handle)
131         return WINED3D_OK;
132
133     TRACE("Setting swapchain %p window from %p to %p.\n",
134             swapchain, swapchain->win_handle, window);
135     swapchain->win_handle = window;
136
137     return WINED3D_OK;
138 }
139
140 HRESULT CDECL wined3d_swapchain_present(struct wined3d_swapchain *swapchain,
141         const RECT *src_rect, const RECT *dst_rect, HWND dst_window_override,
142         const RGNDATA *dirty_region, DWORD flags)
143 {
144     TRACE("swapchain %p, src_rect %s, dst_rect %s, dst_window_override %p, dirty_region %p, flags %#x.\n",
145             swapchain, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect),
146             dst_window_override, dirty_region, flags);
147
148     wined3d_swapchain_set_window(swapchain, dst_window_override);
149
150     return swapchain->swapchain_ops->swapchain_present(swapchain,
151             src_rect, dst_rect, dirty_region, flags);
152 }
153
154 HRESULT CDECL wined3d_swapchain_get_front_buffer_data(const struct wined3d_swapchain *swapchain,
155         IWineD3DSurface *dst_surface)
156 {
157     POINT offset = {0, 0};
158
159     TRACE("swapchain %p, dst_surface %p.\n", swapchain, dst_surface);
160
161     if (swapchain->presentParms.Windowed)
162         MapWindowPoints(swapchain->win_handle, NULL, &offset, 1);
163
164     IWineD3DSurface_BltFast(dst_surface, offset.x, offset.y,
165             (IWineD3DSurface *)swapchain->front_buffer, NULL, 0);
166
167     return WINED3D_OK;
168 }
169
170 HRESULT CDECL wined3d_swapchain_get_back_buffer(const struct wined3d_swapchain *swapchain,
171         UINT back_buffer_idx, WINED3DBACKBUFFER_TYPE type, IWineD3DSurface **back_buffer)
172 {
173     TRACE("swapchain %p, back_buffer_idx %u, type %#x, back_buffer %p.\n",
174             swapchain, back_buffer_idx, type, back_buffer);
175
176     /* Return invalid if there is no backbuffer array, otherwise it will
177      * crash when ddraw is used (there swapchain->back_buffers is always
178      * NULL). We need this because this function is called from
179      * stateblock_init_default_state() to get the default scissorrect
180      * dimensions. */
181     if (!swapchain->back_buffers || back_buffer_idx >= swapchain->presentParms.BackBufferCount)
182     {
183         WARN("Invalid back buffer index.\n");
184         /* Native d3d9 doesn't set NULL here, just as wine's d3d9. But set it
185          * here in wined3d to avoid problems in other libs. */
186         *back_buffer = NULL;
187         return WINED3DERR_INVALIDCALL;
188     }
189
190     *back_buffer = (IWineD3DSurface *)swapchain->back_buffers[back_buffer_idx];
191     if (*back_buffer) IWineD3DSurface_AddRef(*back_buffer);
192
193     TRACE("Returning back buffer %p.\n", *back_buffer);
194
195     return WINED3D_OK;
196 }
197
198 HRESULT CDECL wined3d_swapchain_get_raster_status(const struct wined3d_swapchain *swapchain,
199         WINED3DRASTER_STATUS *raster_status)
200 {
201     static BOOL warned;
202     /* No OpenGL equivalent */
203     if (!warned)
204     {
205         FIXME("swapchain %p, raster_status %p stub!\n", swapchain, raster_status);
206         warned = TRUE;
207     }
208
209     /* Obtaining the raster status is a widely implemented but optional
210      * feature. When this method returns OK Starcraft 2 expects the
211      * raster_status->InVBlank value to actually change over time. To prevent
212      * Starcraft 2 from running in an infinite loop at startup this method
213      * returns INVALIDCALL. */
214     return WINED3DERR_INVALIDCALL;
215 }
216
217 HRESULT CDECL wined3d_swapchain_get_display_mode(const struct wined3d_swapchain *swapchain, WINED3DDISPLAYMODE *mode)
218 {
219     HRESULT hr;
220
221     TRACE("swapchain %p, mode %p.\n", swapchain, mode);
222
223     hr = wined3d_get_adapter_display_mode(swapchain->device->wined3d, swapchain->device->adapter->ordinal, mode);
224
225     TRACE("Returning w %u, h %u, refresh rate %u, format %s.\n",
226             mode->Width, mode->Height, mode->RefreshRate, debug_d3dformat(mode->Format));
227
228     return hr;
229 }
230
231 IWineD3DDevice * CDECL wined3d_swapchain_get_device(const struct wined3d_swapchain *swapchain)
232 {
233     TRACE("swapchain %p.\n", swapchain);
234
235     return (IWineD3DDevice *)swapchain->device;
236 }
237
238 HRESULT CDECL wined3d_swapchain_get_present_parameters(const struct wined3d_swapchain *swapchain,
239         WINED3DPRESENT_PARAMETERS *present_parameters)
240 {
241     TRACE("swapchain %p, present_parameters %p.\n", swapchain, present_parameters);
242
243     *present_parameters = swapchain->presentParms;
244
245     return WINED3D_OK;
246 }
247
248 HRESULT CDECL wined3d_swapchain_set_gamma_ramp(const struct wined3d_swapchain *swapchain,
249         DWORD flags, const WINED3DGAMMARAMP *ramp)
250 {
251     HDC dc;
252
253     TRACE("swapchain %p, flags %#x, ramp %p.\n", swapchain, flags, ramp);
254
255     if (flags)
256         FIXME("Ignoring flags %#x.\n", flags);
257
258     dc = GetDC(swapchain->device_window);
259     SetDeviceGammaRamp(dc, (void *)ramp);
260     ReleaseDC(swapchain->device_window, dc);
261
262     return WINED3D_OK;
263 }
264
265 HRESULT CDECL wined3d_swapchain_get_gamma_ramp(const struct wined3d_swapchain *swapchain,
266         WINED3DGAMMARAMP *ramp)
267 {
268     HDC dc;
269
270     TRACE("swapchain %p, ramp %p.\n", swapchain, ramp);
271
272     dc = GetDC(swapchain->device_window);
273     GetDeviceGammaRamp(dc, ramp);
274     ReleaseDC(swapchain->device_window, dc);
275
276     return WINED3D_OK;
277 }
278
279 /* A GL context is provided by the caller */
280 static void swapchain_blit(struct wined3d_swapchain *swapchain,
281         struct wined3d_context *context, const RECT *src_rect, const RECT *dst_rect)
282 {
283     IWineD3DSurfaceImpl *backbuffer = swapchain->back_buffers[0];
284     IWineD3DDeviceImpl *device = swapchain->device;
285     UINT src_w = src_rect->right - src_rect->left;
286     UINT src_h = src_rect->bottom - src_rect->top;
287     GLenum gl_filter;
288     const struct wined3d_gl_info *gl_info = context->gl_info;
289     RECT win_rect;
290     UINT win_h;
291
292     TRACE("swapchain %p, context %p, src_rect %s, dst_rect %s.\n",
293             swapchain, context, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect));
294
295     if (src_w == dst_rect->right - dst_rect->left && src_h == dst_rect->bottom - dst_rect->top)
296         gl_filter = GL_NEAREST;
297     else
298         gl_filter = GL_LINEAR;
299
300     GetClientRect(swapchain->win_handle, &win_rect);
301     win_h = win_rect.bottom - win_rect.top;
302
303     if (gl_info->fbo_ops.glBlitFramebuffer && is_identity_fixup(backbuffer->resource.format->color_fixup))
304     {
305         ENTER_GL();
306         context_apply_fbo_state_blit(context, GL_READ_FRAMEBUFFER, backbuffer, NULL, SFLAG_INTEXTURE);
307         glReadBuffer(GL_COLOR_ATTACHMENT0);
308         context_check_fbo_status(context, GL_READ_FRAMEBUFFER);
309
310         context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, NULL);
311         context_set_draw_buffer(context, GL_BACK);
312
313         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
314         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
315         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
316         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
317         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
318
319         glDisable(GL_SCISSOR_TEST);
320         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
321
322         /* Note that the texture is upside down */
323         gl_info->fbo_ops.glBlitFramebuffer(src_rect->left, src_rect->top, src_rect->right, src_rect->bottom,
324                 dst_rect->left, win_h - dst_rect->top, dst_rect->right, win_h - dst_rect->bottom,
325                 GL_COLOR_BUFFER_BIT, gl_filter);
326         checkGLcall("Swapchain present blit(EXT_framebuffer_blit)\n");
327         LEAVE_GL();
328     }
329     else
330     {
331         struct wined3d_context *context2;
332         float tex_left = src_rect->left;
333         float tex_top = src_rect->top;
334         float tex_right = src_rect->right;
335         float tex_bottom = src_rect->bottom;
336
337         context2 = context_acquire(device, swapchain->back_buffers[0]);
338         context_apply_blit_state(context2, device);
339
340         if (backbuffer->flags & SFLAG_NORMCOORD)
341         {
342             tex_left /= src_w;
343             tex_right /= src_w;
344             tex_top /= src_h;
345             tex_bottom /= src_h;
346         }
347
348         if (is_complex_fixup(backbuffer->resource.format->color_fixup))
349             gl_filter = GL_NEAREST;
350
351         ENTER_GL();
352         context_bind_fbo(context2, GL_FRAMEBUFFER, NULL);
353
354         /* Set up the texture. The surface is not in a IWineD3D*Texture container,
355          * so there are no d3d texture settings to dirtify
356          */
357         device->blitter->set_shader(device->blit_priv, context2->gl_info, backbuffer);
358         glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MIN_FILTER, gl_filter);
359         glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MAG_FILTER, gl_filter);
360
361         context_set_draw_buffer(context, GL_BACK);
362
363         /* Set the viewport to the destination rectandle, disable any projection
364          * transformation set up by context_apply_blit_state(), and draw a
365          * (-1,-1)-(1,1) quad.
366          *
367          * Back up viewport and matrix to avoid breaking last_was_blit
368          *
369          * Note that context_apply_blit_state() set up viewport and ortho to
370          * match the surface size - we want the GL drawable(=window) size. */
371         glPushAttrib(GL_VIEWPORT_BIT);
372         glViewport(dst_rect->left, win_h - dst_rect->bottom, dst_rect->right, win_h - dst_rect->top);
373         glMatrixMode(GL_PROJECTION);
374         glPushMatrix();
375         glLoadIdentity();
376
377         glBegin(GL_QUADS);
378             /* bottom left */
379             glTexCoord2f(tex_left, tex_bottom);
380             glVertex2i(-1, -1);
381
382             /* top left */
383             glTexCoord2f(tex_left, tex_top);
384             glVertex2i(-1, 1);
385
386             /* top right */
387             glTexCoord2f(tex_right, tex_top);
388             glVertex2i(1, 1);
389
390             /* bottom right */
391             glTexCoord2f(tex_right, tex_bottom);
392             glVertex2i(1, -1);
393         glEnd();
394
395         glPopMatrix();
396         glPopAttrib();
397
398         device->blitter->unset_shader(context->gl_info);
399         checkGLcall("Swapchain present blit(manual)\n");
400         LEAVE_GL();
401
402         context_release(context2);
403     }
404 }
405
406 static HRESULT swapchain_gl_present(struct wined3d_swapchain *swapchain, const RECT *src_rect_in,
407         const RECT *dst_rect_in, const RGNDATA *dirty_region, DWORD flags)
408 {
409     const struct wined3d_gl_info *gl_info;
410     struct wined3d_context *context;
411     RECT src_rect, dst_rect;
412     BOOL render_to_fbo;
413
414     context = context_acquire(swapchain->device, swapchain->back_buffers[0]);
415     if (!context->valid)
416     {
417         context_release(context);
418         WARN("Invalid context, skipping present.\n");
419         return WINED3D_OK;
420     }
421
422     gl_info = context->gl_info;
423
424     /* Render the cursor onto the back buffer, using our nifty directdraw blitting code :-) */
425     if (swapchain->device->bCursorVisible && swapchain->device->cursorTexture)
426     {
427         IWineD3DSurfaceImpl cursor;
428         RECT destRect =
429         {
430             swapchain->device->xScreenSpace - swapchain->device->xHotSpot,
431             swapchain->device->yScreenSpace - swapchain->device->yHotSpot,
432             swapchain->device->xScreenSpace + swapchain->device->cursorWidth - swapchain->device->xHotSpot,
433             swapchain->device->yScreenSpace + swapchain->device->cursorHeight - swapchain->device->yHotSpot,
434         };
435         TRACE("Rendering the cursor. Creating fake surface at %p\n", &cursor);
436         /* Build a fake surface to call the Blitting code. It is not possible to use the interface passed by
437          * the application because we are only supposed to copy the information out. Using a fake surface
438          * allows to use the Blitting engine and avoid copying the whole texture -> render target blitting code.
439          */
440         memset(&cursor, 0, sizeof(cursor));
441         cursor.lpVtbl = &IWineD3DSurface_Vtbl;
442         cursor.resource.ref = 1;
443         cursor.resource.device = swapchain->device;
444         cursor.resource.pool = WINED3DPOOL_SCRATCH;
445         cursor.resource.format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
446         cursor.resource.resourceType = WINED3DRTYPE_SURFACE;
447         cursor.texture_name = swapchain->device->cursorTexture;
448         cursor.texture_target = GL_TEXTURE_2D;
449         cursor.texture_level = 0;
450         cursor.resource.width = swapchain->device->cursorWidth;
451         cursor.resource.height = swapchain->device->cursorHeight;
452         /* The cursor must have pow2 sizes */
453         cursor.pow2Width = cursor.resource.width;
454         cursor.pow2Height = cursor.resource.height;
455         /* The surface is in the texture */
456         cursor.flags |= SFLAG_INTEXTURE;
457         /* DDBLT_KEYSRC will cause BltOverride to enable the alpha test with GL_NOTEQUAL, 0.0,
458          * which is exactly what we want :-)
459          */
460         if (swapchain->presentParms.Windowed)
461             MapWindowPoints(NULL, swapchain->win_handle, (LPPOINT)&destRect, 2);
462         IWineD3DSurface_Blt((IWineD3DSurface *)swapchain->back_buffers[0], &destRect,
463                 (IWineD3DSurface *)&cursor, NULL, WINEDDBLT_KEYSRC, NULL, WINED3DTEXF_POINT);
464     }
465
466     if (swapchain->device->logo_surface)
467     {
468         /* Blit the logo into the upper left corner of the drawable. */
469         IWineD3DSurface_BltFast((IWineD3DSurface *)swapchain->back_buffers[0], 0, 0,
470                 swapchain->device->logo_surface, NULL, WINEDDBLTFAST_SRCCOLORKEY);
471     }
472
473     TRACE("Presenting HDC %p.\n", context->hdc);
474
475     render_to_fbo = swapchain->render_to_fbo;
476
477     if (src_rect_in)
478     {
479         src_rect = *src_rect_in;
480         if (!render_to_fbo && (src_rect.left || src_rect.top
481                 || src_rect.right != swapchain->presentParms.BackBufferWidth
482                 || src_rect.bottom != swapchain->presentParms.BackBufferHeight))
483         {
484             render_to_fbo = TRUE;
485         }
486     }
487     else
488     {
489         src_rect.left = 0;
490         src_rect.top = 0;
491         src_rect.right = swapchain->presentParms.BackBufferWidth;
492         src_rect.bottom = swapchain->presentParms.BackBufferHeight;
493     }
494
495     if (dst_rect_in)
496         dst_rect = *dst_rect_in;
497     else
498         GetClientRect(swapchain->win_handle, &dst_rect);
499
500     if (!render_to_fbo && (dst_rect.left || dst_rect.top
501             || dst_rect.right != swapchain->presentParms.BackBufferWidth
502             || dst_rect.bottom != swapchain->presentParms.BackBufferHeight))
503     {
504         render_to_fbo = TRUE;
505     }
506
507     /* Rendering to a window of different size, presenting partial rectangles,
508      * or rendering to a different window needs help from FBO_blit or a textured
509      * draw. Render the swapchain to a FBO in the future.
510      *
511      * Note that FBO_blit from the backbuffer to the frontbuffer cannot solve
512      * all these issues - this fails if the window is smaller than the backbuffer.
513      */
514     if (!swapchain->render_to_fbo && render_to_fbo && wined3d_settings.offscreen_rendering_mode == ORM_FBO)
515     {
516         surface_load_location(swapchain->back_buffers[0], SFLAG_INTEXTURE, NULL);
517         surface_modify_location(swapchain->back_buffers[0], SFLAG_INDRAWABLE, FALSE);
518         swapchain->render_to_fbo = TRUE;
519     }
520
521     if (swapchain->render_to_fbo)
522     {
523         /* This codepath should only be hit with the COPY swapeffect. Otherwise a backbuffer-
524          * window size mismatch is impossible(fullscreen) and src and dst rectangles are
525          * not allowed(they need the COPY swapeffect)
526          *
527          * The DISCARD swap effect is ok as well since any backbuffer content is allowed after
528          * the swap. */
529         if (swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP)
530             FIXME("Render-to-fbo with WINED3DSWAPEFFECT_FLIP\n");
531
532         swapchain_blit(swapchain, context, &src_rect, &dst_rect);
533     }
534
535     if (swapchain->num_contexts > 1)
536         wglFinish();
537     SwapBuffers(context->hdc); /* TODO: cycle through the swapchain buffers */
538
539     TRACE("SwapBuffers called, Starting new frame\n");
540     /* FPS support */
541     if (TRACE_ON(fps))
542     {
543         DWORD time = GetTickCount();
544         ++swapchain->frames;
545
546         /* every 1.5 seconds */
547         if (time - swapchain->prev_time > 1500)
548         {
549             TRACE_(fps)("%p @ approx %.2ffps\n",
550                     swapchain, 1000.0 * swapchain->frames / (time - swapchain->prev_time));
551             swapchain->prev_time = time;
552             swapchain->frames = 0;
553         }
554     }
555
556     /* This is disabled, but the code left in for debug purposes.
557      *
558      * Since we're allowed to modify the new back buffer on a D3DSWAPEFFECT_DISCARD flip,
559      * we can clear it with some ugly color to make bad drawing visible and ease debugging.
560      * The Debug runtime does the same on Windows. However, a few games do not redraw the
561      * screen properly, like Max Payne 2, which leaves a few pixels undefined.
562      *
563      * Tests show that the content of the back buffer after a discard flip is indeed not
564      * reliable, so no game can depend on the exact content. However, it resembles the
565      * old contents in some way, for example by showing fragments at other locations. In
566      * general, the color theme is still intact. So Max payne, which draws rather dark scenes
567      * gets a dark background image. If we clear it with a bright ugly color, the game's
568      * bug shows up much more than it does on Windows, and the players see single pixels
569      * with wrong colors.
570      * (The Max Payne bug has been confirmed on Windows with the debug runtime) */
571     if (FALSE && swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD)
572     {
573         TRACE("Clearing the color buffer with cyan color\n");
574
575         IWineD3DDevice_Clear((IWineD3DDevice *)swapchain->device, 0, NULL,
576                 WINED3DCLEAR_TARGET, 0xff00ffff, 1.0f, 0);
577     }
578
579     if (!swapchain->render_to_fbo && ((swapchain->front_buffer->flags & SFLAG_INSYSMEM)
580             || (swapchain->back_buffers[0]->flags & SFLAG_INSYSMEM)))
581     {
582         /* Both memory copies of the surfaces are ok, flip them around too instead of dirtifying
583          * Doesn't work with render_to_fbo because we're not flipping
584          */
585         IWineD3DSurfaceImpl *front = swapchain->front_buffer;
586         IWineD3DSurfaceImpl *back = swapchain->back_buffers[0];
587
588         if(front->resource.size == back->resource.size) {
589             DWORD fbflags;
590             flip_surface(front, back);
591
592             /* Tell the front buffer surface that is has been modified. However,
593              * the other locations were preserved during that, so keep the flags.
594              * This serves to update the emulated overlay, if any. */
595             fbflags = front->flags;
596             surface_modify_location(front, SFLAG_INDRAWABLE, TRUE);
597             front->flags = fbflags;
598         }
599         else
600         {
601             surface_modify_location(front, SFLAG_INDRAWABLE, TRUE);
602             surface_modify_location(back, SFLAG_INDRAWABLE, TRUE);
603         }
604     }
605     else
606     {
607         surface_modify_location(swapchain->front_buffer, SFLAG_INDRAWABLE, TRUE);
608         /* If the swapeffect is DISCARD, the back buffer is undefined. That means the SYSMEM
609          * and INTEXTURE copies can keep their old content if they have any defined content.
610          * If the swapeffect is COPY, the content remains the same. If it is FLIP however,
611          * the texture / sysmem copy needs to be reloaded from the drawable
612          */
613         if (swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP)
614             surface_modify_location(swapchain->back_buffers[0], SFLAG_INDRAWABLE, TRUE);
615     }
616
617     if (swapchain->device->depth_stencil)
618     {
619         if (swapchain->presentParms.Flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
620                 || swapchain->device->depth_stencil->flags & SFLAG_DISCARD)
621         {
622             surface_modify_ds_location(swapchain->device->depth_stencil, SFLAG_DS_DISCARDED,
623                     swapchain->device->depth_stencil->resource.width,
624                     swapchain->device->depth_stencil->resource.height);
625             if (swapchain->device->depth_stencil == swapchain->device->onscreen_depth_stencil)
626             {
627                 IWineD3DSurface_Release((IWineD3DSurface *)swapchain->device->onscreen_depth_stencil);
628                 swapchain->device->onscreen_depth_stencil = NULL;
629             }
630         }
631     }
632
633     context_release(context);
634
635     TRACE("returning\n");
636     return WINED3D_OK;
637 }
638
639 static const struct wined3d_swapchain_ops swapchain_gl_ops =
640 {
641     swapchain_gl_present,
642 };
643
644 /* Helper function that blits the front buffer contents to the target window. */
645 void x11_copy_to_screen(struct wined3d_swapchain *swapchain, const RECT *rect)
646 {
647     IWineD3DSurfaceImpl *front;
648     POINT offset = {0, 0};
649     HDC src_dc, dst_dc;
650     RECT draw_rect;
651     HWND window;
652
653     TRACE("swapchain %p, rect %s.\n", swapchain, wine_dbgstr_rect(rect));
654
655     front = swapchain->front_buffer;
656     if (!(front->resource.usage & WINED3DUSAGE_RENDERTARGET))
657         return;
658
659     TRACE("Copying surface %p to screen.\n", front);
660
661     src_dc = front->hDC;
662     window = swapchain->win_handle;
663     dst_dc = GetDCEx(window, 0, DCX_CLIPSIBLINGS | DCX_CACHE);
664
665     /* Front buffer coordinates are screen coordinates. Map them to the
666      * destination window if not fullscreened. */
667     if (swapchain->presentParms.Windowed)
668         ClientToScreen(window, &offset);
669
670     TRACE("offset %s.\n", wine_dbgstr_point(&offset));
671
672 #if 0
673     /* FIXME: This doesn't work... if users really want to run
674      * X in 8bpp, then we need to call directly into display.drv
675      * (or Wine's equivalent), and force a private colormap
676      * without default entries. */
677     if (front->palette)
678     {
679         SelectPalette(dst_dc, front->palette->hpal, FALSE);
680         RealizePalette(dst_dc); /* sends messages => deadlocks */
681     }
682 #endif
683
684     draw_rect.left = 0;
685     draw_rect.right = front->resource.width;
686     draw_rect.top = 0;
687     draw_rect.bottom = front->resource.height;
688
689 #if 0
690     /* TODO: Support clippers. */
691     if (front->clipper)
692     {
693         RECT xrc;
694         HWND hwnd = ((IWineD3DClipperImpl *)front->clipper)->hWnd;
695         if (hwnd && GetClientRect(hwnd,&xrc))
696         {
697             OffsetRect(&xrc, offset.x, offset.y);
698             IntersectRect(&draw_rect, &draw_rect, &xrc);
699         }
700     }
701 #endif
702
703     if (!rect)
704     {
705         /* Only use this if the caller did not pass a rectangle, since
706          * due to double locking this could be the wrong one... */
707         if (front->lockedRect.left != front->lockedRect.right)
708             IntersectRect(&draw_rect, &draw_rect, &front->lockedRect);
709     }
710     else
711     {
712         IntersectRect(&draw_rect, &draw_rect, rect);
713     }
714
715     BitBlt(dst_dc, draw_rect.left - offset.x, draw_rect.top - offset.y,
716             draw_rect.right - draw_rect.left, draw_rect.bottom - draw_rect.top,
717             src_dc, draw_rect.left, draw_rect.top, SRCCOPY);
718     ReleaseDC(window, dst_dc);
719 }
720
721 static HRESULT swapchain_gdi_present(struct wined3d_swapchain *swapchain, const RECT *src_rect_in,
722         const RECT *dst_rect_in, const RGNDATA *dirty_region, DWORD flags)
723 {
724     IWineD3DSurfaceImpl *front, *back;
725
726     if (!swapchain->back_buffers)
727     {
728         WARN("Swapchain doesn't have a backbuffer, returning WINED3DERR_INVALIDCALL\n");
729         return WINED3DERR_INVALIDCALL;
730     }
731     front = swapchain->front_buffer;
732     back = swapchain->back_buffers[0];
733
734     /* Flip the DC. */
735     {
736         HDC tmp;
737         tmp = front->hDC;
738         front->hDC = back->hDC;
739         back->hDC = tmp;
740     }
741
742     /* Flip the DIBsection. */
743     {
744         HBITMAP tmp;
745         tmp = front->dib.DIBsection;
746         front->dib.DIBsection = back->dib.DIBsection;
747         back->dib.DIBsection = tmp;
748     }
749
750     /* Flip the surface data. */
751     {
752         void *tmp;
753
754         tmp = front->dib.bitmap_data;
755         front->dib.bitmap_data = back->dib.bitmap_data;
756         back->dib.bitmap_data = tmp;
757
758         tmp = front->resource.allocatedMemory;
759         front->resource.allocatedMemory = back->resource.allocatedMemory;
760         back->resource.allocatedMemory = tmp;
761
762         if (front->resource.heapMemory)
763             ERR("GDI Surface %p has heap memory allocated.\n", front);
764
765         if (back->resource.heapMemory)
766             ERR("GDI Surface %p has heap memory allocated.\n", back);
767     }
768
769     /* Client_memory should not be different, but just in case. */
770     {
771         BOOL tmp;
772         tmp = front->dib.client_memory;
773         front->dib.client_memory = back->dib.client_memory;
774         back->dib.client_memory = tmp;
775     }
776
777     /* FPS support */
778     if (TRACE_ON(fps))
779     {
780         static LONG prev_time, frames;
781         DWORD time = GetTickCount();
782
783         ++frames;
784
785         /* every 1.5 seconds */
786         if (time - prev_time > 1500)
787         {
788             TRACE_(fps)("@ approx %.2ffps\n", 1000.0 * frames / (time - prev_time));
789             prev_time = time;
790             frames = 0;
791         }
792     }
793
794     x11_copy_to_screen(swapchain, NULL);
795
796     return WINED3D_OK;
797 }
798
799 static const struct wined3d_swapchain_ops swapchain_gdi_ops =
800 {
801     swapchain_gdi_present,
802 };
803
804 /* Do not call while under the GL lock. */
805 HRESULT swapchain_init(struct wined3d_swapchain *swapchain, WINED3DSURFTYPE surface_type,
806         IWineD3DDeviceImpl *device, WINED3DPRESENT_PARAMETERS *present_parameters,
807         void *parent, const struct wined3d_parent_ops *parent_ops)
808 {
809     const struct wined3d_adapter *adapter = device->adapter;
810     const struct wined3d_format *format;
811     BOOL displaymode_set = FALSE;
812     WINED3DDISPLAYMODE mode;
813     RECT client_rect;
814     HWND window;
815     HRESULT hr;
816     UINT i;
817
818     if (present_parameters->BackBufferCount > WINED3DPRESENT_BACK_BUFFER_MAX)
819     {
820         FIXME("The application requested %u back buffers, this is not supported.\n",
821                 present_parameters->BackBufferCount);
822         return WINED3DERR_INVALIDCALL;
823     }
824
825     if (present_parameters->BackBufferCount > 1)
826     {
827         FIXME("The application requested more than one back buffer, this is not properly supported.\n"
828                 "Please configure the application to use double buffering (1 back buffer) if possible.\n");
829     }
830
831     switch (surface_type)
832     {
833         case SURFACE_GDI:
834             swapchain->swapchain_ops = &swapchain_gdi_ops;
835             break;
836
837         case SURFACE_OPENGL:
838             swapchain->swapchain_ops = &swapchain_gl_ops;
839             break;
840
841         case SURFACE_UNKNOWN:
842             FIXME("Caller tried to create a SURFACE_UNKNOWN swapchain.\n");
843             return WINED3DERR_INVALIDCALL;
844     }
845
846     window = present_parameters->hDeviceWindow ? present_parameters->hDeviceWindow : device->createParms.hFocusWindow;
847
848     swapchain->device = device;
849     swapchain->parent = parent;
850     swapchain->parent_ops = parent_ops;
851     swapchain->ref = 1;
852     swapchain->win_handle = window;
853     swapchain->device_window = window;
854
855     wined3d_get_adapter_display_mode(device->wined3d, adapter->ordinal, &mode);
856     swapchain->orig_width = mode.Width;
857     swapchain->orig_height = mode.Height;
858     swapchain->orig_fmt = mode.Format;
859     format = wined3d_get_format(&adapter->gl_info, mode.Format);
860
861     GetClientRect(window, &client_rect);
862     if (present_parameters->Windowed
863             && (!present_parameters->BackBufferWidth || !present_parameters->BackBufferHeight
864             || present_parameters->BackBufferFormat == WINED3DFMT_UNKNOWN))
865     {
866
867         if (!present_parameters->BackBufferWidth)
868         {
869             present_parameters->BackBufferWidth = client_rect.right;
870             TRACE("Updating width to %u.\n", present_parameters->BackBufferWidth);
871         }
872
873         if (!present_parameters->BackBufferHeight)
874         {
875             present_parameters->BackBufferHeight = client_rect.bottom;
876             TRACE("Updating height to %u.\n", present_parameters->BackBufferHeight);
877         }
878
879         if (present_parameters->BackBufferFormat == WINED3DFMT_UNKNOWN)
880         {
881             present_parameters->BackBufferFormat = swapchain->orig_fmt;
882             TRACE("Updating format to %s.\n", debug_d3dformat(swapchain->orig_fmt));
883         }
884     }
885     swapchain->presentParms = *present_parameters;
886
887     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
888             && present_parameters->BackBufferCount
889             && (present_parameters->BackBufferWidth != client_rect.right
890             || present_parameters->BackBufferHeight != client_rect.bottom))
891     {
892         TRACE("Rendering to FBO. Backbuffer %ux%u, window %ux%u.\n",
893                 present_parameters->BackBufferWidth,
894                 present_parameters->BackBufferHeight,
895                 client_rect.right, client_rect.bottom);
896         swapchain->render_to_fbo = TRUE;
897     }
898
899     TRACE("Creating front buffer.\n");
900     hr = IWineD3DDeviceParent_CreateRenderTarget(device->device_parent, parent,
901             swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
902             swapchain->presentParms.BackBufferFormat, swapchain->presentParms.MultiSampleType,
903             swapchain->presentParms.MultiSampleQuality, TRUE /* Lockable */,
904             (IWineD3DSurface **)&swapchain->front_buffer);
905     if (FAILED(hr))
906     {
907         WARN("Failed to create front buffer, hr %#x.\n", hr);
908         goto err;
909     }
910
911     surface_set_container(swapchain->front_buffer, WINED3D_CONTAINER_SWAPCHAIN, swapchain);
912     if (surface_type == SURFACE_OPENGL)
913     {
914         surface_modify_location(swapchain->front_buffer, SFLAG_INDRAWABLE, TRUE);
915     }
916
917     /* MSDN says we're only allowed a single fullscreen swapchain per device,
918      * so we should really check to see if there is a fullscreen swapchain
919      * already. Does a single head count as full screen? */
920
921     if (!present_parameters->Windowed)
922     {
923         WINED3DDISPLAYMODE mode;
924
925         /* Change the display settings */
926         mode.Width = present_parameters->BackBufferWidth;
927         mode.Height = present_parameters->BackBufferHeight;
928         mode.Format = present_parameters->BackBufferFormat;
929         mode.RefreshRate = present_parameters->FullScreen_RefreshRateInHz;
930
931         hr = IWineD3DDevice_SetDisplayMode((IWineD3DDevice *)device, 0, &mode);
932         if (FAILED(hr))
933         {
934             WARN("Failed to set display mode, hr %#x.\n", hr);
935             goto err;
936         }
937         displaymode_set = TRUE;
938     }
939
940     if (surface_type == SURFACE_OPENGL)
941     {
942         static const enum wined3d_format_id formats[] =
943         {
944             WINED3DFMT_D24_UNORM_S8_UINT,
945             WINED3DFMT_D32_UNORM,
946             WINED3DFMT_R24_UNORM_X8_TYPELESS,
947             WINED3DFMT_D16_UNORM,
948             WINED3DFMT_S1_UINT_D15_UNORM
949         };
950
951         const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
952
953         swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(swapchain->context));
954         if (!swapchain->context)
955         {
956             ERR("Failed to create the context array.\n");
957             hr = E_OUTOFMEMORY;
958             goto err;
959         }
960         swapchain->num_contexts = 1;
961
962         /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
963          * You are able to add a depth + stencil surface at a later stage when you need it.
964          * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
965          * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
966          * context, need torecreate shaders, textures and other resources.
967          *
968          * The context manager already takes care of the state problem and for the other tasks code from Reset
969          * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
970          * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
971          * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
972          * issue needs to be fixed. */
973         for (i = 0; i < (sizeof(formats) / sizeof(*formats)); i++)
974         {
975             swapchain->ds_format = wined3d_get_format(gl_info, formats[i]);
976             swapchain->context[0] = context_create(swapchain, swapchain->front_buffer, swapchain->ds_format);
977             if (swapchain->context[0]) break;
978             TRACE("Depth stencil format %s is not supported, trying next format\n",
979                   debug_d3dformat(formats[i]));
980         }
981
982         if (!swapchain->context[0])
983         {
984             WARN("Failed to create context.\n");
985             hr = WINED3DERR_NOTAVAILABLE;
986             goto err;
987         }
988
989         if (!present_parameters->EnableAutoDepthStencil
990                 || swapchain->presentParms.AutoDepthStencilFormat != swapchain->ds_format->id)
991         {
992             FIXME("Add OpenGL context recreation support to context_validate_onscreen_formats\n");
993         }
994         context_release(swapchain->context[0]);
995     }
996
997     if (swapchain->presentParms.BackBufferCount > 0)
998     {
999         swapchain->back_buffers = HeapAlloc(GetProcessHeap(), 0,
1000                 sizeof(*swapchain->back_buffers) * swapchain->presentParms.BackBufferCount);
1001         if (!swapchain->back_buffers)
1002         {
1003             ERR("Failed to allocate backbuffer array memory.\n");
1004             hr = E_OUTOFMEMORY;
1005             goto err;
1006         }
1007
1008         for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
1009         {
1010             TRACE("Creating back buffer %u.\n", i);
1011             hr = IWineD3DDeviceParent_CreateRenderTarget(device->device_parent, parent,
1012                     swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
1013                     swapchain->presentParms.BackBufferFormat, swapchain->presentParms.MultiSampleType,
1014                     swapchain->presentParms.MultiSampleQuality, TRUE /* Lockable */,
1015                     (IWineD3DSurface **)&swapchain->back_buffers[i]);
1016             if (FAILED(hr))
1017             {
1018                 WARN("Failed to create back buffer %u, hr %#x.\n", i, hr);
1019                 goto err;
1020             }
1021
1022             surface_set_container(swapchain->back_buffers[i], WINED3D_CONTAINER_SWAPCHAIN, swapchain);
1023         }
1024     }
1025
1026     /* Swapchains share the depth/stencil buffer, so only create a single depthstencil surface. */
1027     if (present_parameters->EnableAutoDepthStencil && surface_type == SURFACE_OPENGL)
1028     {
1029         TRACE("Creating depth/stencil buffer.\n");
1030         if (!device->auto_depth_stencil)
1031         {
1032             hr = IWineD3DDeviceParent_CreateDepthStencilSurface(device->device_parent,
1033                     swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
1034                     swapchain->presentParms.AutoDepthStencilFormat, swapchain->presentParms.MultiSampleType,
1035                     swapchain->presentParms.MultiSampleQuality, FALSE /* FIXME: Discard */,
1036                     (IWineD3DSurface **)&device->auto_depth_stencil);
1037             if (FAILED(hr))
1038             {
1039                 WARN("Failed to create the auto depth stencil, hr %#x.\n", hr);
1040                 goto err;
1041             }
1042
1043             surface_set_container(device->auto_depth_stencil, WINED3D_CONTAINER_NONE, NULL);
1044         }
1045     }
1046
1047     wined3d_swapchain_get_gamma_ramp(swapchain, &swapchain->orig_gamma);
1048
1049     return WINED3D_OK;
1050
1051 err:
1052     if (displaymode_set)
1053     {
1054         DEVMODEW devmode;
1055
1056         ClipCursor(NULL);
1057
1058         /* Change the display settings */
1059         memset(&devmode, 0, sizeof(devmode));
1060         devmode.dmSize = sizeof(devmode);
1061         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1062         devmode.dmBitsPerPel = format->byte_count * CHAR_BIT;
1063         devmode.dmPelsWidth = swapchain->orig_width;
1064         devmode.dmPelsHeight = swapchain->orig_height;
1065         ChangeDisplaySettingsExW(adapter->DeviceName, &devmode, NULL, CDS_FULLSCREEN, NULL);
1066     }
1067
1068     if (swapchain->back_buffers)
1069     {
1070         for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
1071         {
1072             if (swapchain->back_buffers[i]) IWineD3DSurface_Release((IWineD3DSurface *)swapchain->back_buffers[i]);
1073         }
1074         HeapFree(GetProcessHeap(), 0, swapchain->back_buffers);
1075     }
1076
1077     if (swapchain->context)
1078     {
1079         if (swapchain->context[0])
1080         {
1081             context_release(swapchain->context[0]);
1082             context_destroy(device, swapchain->context[0]);
1083             swapchain->num_contexts = 0;
1084         }
1085         HeapFree(GetProcessHeap(), 0, swapchain->context);
1086     }
1087
1088     if (swapchain->front_buffer) IWineD3DSurface_Release((IWineD3DSurface *)swapchain->front_buffer);
1089
1090     return hr;
1091 }
1092
1093 /* Do not call while under the GL lock. */
1094 static struct wined3d_context *swapchain_create_context(struct wined3d_swapchain *swapchain)
1095 {
1096     struct wined3d_context **newArray;
1097     struct wined3d_context *ctx;
1098
1099     TRACE("Creating a new context for swapchain %p, thread %u.\n", swapchain, GetCurrentThreadId());
1100
1101     if (!(ctx = context_create(swapchain, swapchain->front_buffer, swapchain->ds_format)))
1102     {
1103         ERR("Failed to create a new context for the swapchain\n");
1104         return NULL;
1105     }
1106     context_release(ctx);
1107
1108     newArray = HeapAlloc(GetProcessHeap(), 0, sizeof(*newArray) * (swapchain->num_contexts + 1));
1109     if(!newArray) {
1110         ERR("Out of memory when trying to allocate a new context array\n");
1111         context_destroy(swapchain->device, ctx);
1112         return NULL;
1113     }
1114     memcpy(newArray, swapchain->context, sizeof(*newArray) * swapchain->num_contexts);
1115     HeapFree(GetProcessHeap(), 0, swapchain->context);
1116     newArray[swapchain->num_contexts] = ctx;
1117     swapchain->context = newArray;
1118     swapchain->num_contexts++;
1119
1120     TRACE("Returning context %p\n", ctx);
1121     return ctx;
1122 }
1123
1124 struct wined3d_context *swapchain_get_context(struct wined3d_swapchain *swapchain)
1125 {
1126     DWORD tid = GetCurrentThreadId();
1127     unsigned int i;
1128
1129     for (i = 0; i < swapchain->num_contexts; ++i)
1130     {
1131         if (swapchain->context[i]->tid == tid)
1132             return swapchain->context[i];
1133     }
1134
1135     /* Create a new context for the thread */
1136     return swapchain_create_context(swapchain);
1137 }
1138
1139 void get_drawable_size_swapchain(struct wined3d_context *context, UINT *width, UINT *height)
1140 {
1141     /* The drawable size of an onscreen drawable is the surface size.
1142      * (Actually: The window size, but the surface is created in window size) */
1143     *width = context->current_rt->resource.width;
1144     *height = context->current_rt->resource.height;
1145 }