wined3d: Pass a wined3d_color struct to wined3d_device_clear().
[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 (wined3d_surface_decref(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 (wined3d_surface_decref(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         wined3d_device_set_display_mode(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         struct wined3d_surface *dst_surface)
156 {
157     struct wined3d_surface *src_surface;
158     RECT src_rect, dst_rect;
159
160     TRACE("swapchain %p, dst_surface %p.\n", swapchain, dst_surface);
161
162     src_surface = swapchain->front_buffer;
163     SetRect(&src_rect, 0, 0, src_surface->resource.width, src_surface->resource.height);
164     dst_rect = src_rect;
165
166     if (swapchain->presentParms.Windowed)
167     {
168         MapWindowPoints(swapchain->win_handle, NULL, (POINT *)&dst_rect, 2);
169         FIXME("Using destination rect %s in windowed mode, this is likely wrong.\n",
170                 wine_dbgstr_rect(&dst_rect));
171     }
172
173     return wined3d_surface_blt(dst_surface, &dst_rect, src_surface, &src_rect, 0, NULL, WINED3DTEXF_POINT);
174 }
175
176 HRESULT CDECL wined3d_swapchain_get_back_buffer(const struct wined3d_swapchain *swapchain,
177         UINT back_buffer_idx, WINED3DBACKBUFFER_TYPE type, struct wined3d_surface **back_buffer)
178 {
179     TRACE("swapchain %p, back_buffer_idx %u, type %#x, back_buffer %p.\n",
180             swapchain, back_buffer_idx, type, back_buffer);
181
182     /* Return invalid if there is no backbuffer array, otherwise it will
183      * crash when ddraw is used (there swapchain->back_buffers is always
184      * NULL). We need this because this function is called from
185      * stateblock_init_default_state() to get the default scissorrect
186      * dimensions. */
187     if (!swapchain->back_buffers || back_buffer_idx >= swapchain->presentParms.BackBufferCount)
188     {
189         WARN("Invalid back buffer index.\n");
190         /* Native d3d9 doesn't set NULL here, just as wine's d3d9. But set it
191          * here in wined3d to avoid problems in other libs. */
192         *back_buffer = NULL;
193         return WINED3DERR_INVALIDCALL;
194     }
195
196     *back_buffer = swapchain->back_buffers[back_buffer_idx];
197     if (*back_buffer)
198         wined3d_surface_incref(*back_buffer);
199
200     TRACE("Returning back buffer %p.\n", *back_buffer);
201
202     return WINED3D_OK;
203 }
204
205 HRESULT CDECL wined3d_swapchain_get_raster_status(const struct wined3d_swapchain *swapchain,
206         WINED3DRASTER_STATUS *raster_status)
207 {
208     static BOOL warned;
209     /* No OpenGL equivalent */
210     if (!warned)
211     {
212         FIXME("swapchain %p, raster_status %p stub!\n", swapchain, raster_status);
213         warned = TRUE;
214     }
215
216     /* Obtaining the raster status is a widely implemented but optional
217      * feature. When this method returns OK StarCraft 2 expects the
218      * raster_status->InVBlank value to actually change over time. To prevent
219      * StarCraft 2 from running in an infinite loop at startup this method
220      * returns INVALIDCALL. */
221     return WINED3DERR_INVALIDCALL;
222 }
223
224 HRESULT CDECL wined3d_swapchain_get_display_mode(const struct wined3d_swapchain *swapchain, WINED3DDISPLAYMODE *mode)
225 {
226     HRESULT hr;
227
228     TRACE("swapchain %p, mode %p.\n", swapchain, mode);
229
230     hr = wined3d_get_adapter_display_mode(swapchain->device->wined3d, swapchain->device->adapter->ordinal, mode);
231
232     TRACE("Returning w %u, h %u, refresh rate %u, format %s.\n",
233             mode->Width, mode->Height, mode->RefreshRate, debug_d3dformat(mode->Format));
234
235     return hr;
236 }
237
238 struct wined3d_device * CDECL wined3d_swapchain_get_device(const struct wined3d_swapchain *swapchain)
239 {
240     TRACE("swapchain %p.\n", swapchain);
241
242     return swapchain->device;
243 }
244
245 HRESULT CDECL wined3d_swapchain_get_present_parameters(const struct wined3d_swapchain *swapchain,
246         WINED3DPRESENT_PARAMETERS *present_parameters)
247 {
248     TRACE("swapchain %p, present_parameters %p.\n", swapchain, present_parameters);
249
250     *present_parameters = swapchain->presentParms;
251
252     return WINED3D_OK;
253 }
254
255 HRESULT CDECL wined3d_swapchain_set_gamma_ramp(const struct wined3d_swapchain *swapchain,
256         DWORD flags, const WINED3DGAMMARAMP *ramp)
257 {
258     HDC dc;
259
260     TRACE("swapchain %p, flags %#x, ramp %p.\n", swapchain, flags, ramp);
261
262     if (flags)
263         FIXME("Ignoring flags %#x.\n", flags);
264
265     dc = GetDC(swapchain->device_window);
266     SetDeviceGammaRamp(dc, (void *)ramp);
267     ReleaseDC(swapchain->device_window, dc);
268
269     return WINED3D_OK;
270 }
271
272 HRESULT CDECL wined3d_swapchain_get_gamma_ramp(const struct wined3d_swapchain *swapchain,
273         WINED3DGAMMARAMP *ramp)
274 {
275     HDC dc;
276
277     TRACE("swapchain %p, ramp %p.\n", swapchain, ramp);
278
279     dc = GetDC(swapchain->device_window);
280     GetDeviceGammaRamp(dc, ramp);
281     ReleaseDC(swapchain->device_window, dc);
282
283     return WINED3D_OK;
284 }
285
286 /* A GL context is provided by the caller */
287 static void swapchain_blit(const struct wined3d_swapchain *swapchain,
288         struct wined3d_context *context, const RECT *src_rect, const RECT *dst_rect)
289 {
290     struct wined3d_surface *backbuffer = swapchain->back_buffers[0];
291     UINT src_w = src_rect->right - src_rect->left;
292     UINT src_h = src_rect->bottom - src_rect->top;
293     GLenum gl_filter;
294     const struct wined3d_gl_info *gl_info = context->gl_info;
295     RECT win_rect;
296     UINT win_h;
297
298     TRACE("swapchain %p, context %p, src_rect %s, dst_rect %s.\n",
299             swapchain, context, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect));
300
301     if (src_w == dst_rect->right - dst_rect->left && src_h == dst_rect->bottom - dst_rect->top)
302         gl_filter = GL_NEAREST;
303     else
304         gl_filter = GL_LINEAR;
305
306     GetClientRect(swapchain->win_handle, &win_rect);
307     win_h = win_rect.bottom - win_rect.top;
308
309     if (gl_info->fbo_ops.glBlitFramebuffer && is_identity_fixup(backbuffer->resource.format->color_fixup))
310     {
311         DWORD location = SFLAG_INTEXTURE;
312
313         if (backbuffer->resource.multisample_type)
314         {
315             location = SFLAG_INRB_RESOLVED;
316             surface_load_location(backbuffer, location, NULL);
317         }
318
319         ENTER_GL();
320         context_apply_fbo_state_blit(context, GL_READ_FRAMEBUFFER, backbuffer, NULL, location);
321         glReadBuffer(GL_COLOR_ATTACHMENT0);
322         context_check_fbo_status(context, GL_READ_FRAMEBUFFER);
323
324         context_apply_fbo_state_blit(context, GL_DRAW_FRAMEBUFFER, swapchain->front_buffer, NULL, SFLAG_INDRAWABLE);
325         context_set_draw_buffer(context, GL_BACK);
326         context_invalidate_state(context, STATE_FRAMEBUFFER);
327
328         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
329         context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
330         context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
331         context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
332         context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
333
334         glDisable(GL_SCISSOR_TEST);
335         context_invalidate_state(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
336
337         /* Note that the texture is upside down */
338         gl_info->fbo_ops.glBlitFramebuffer(src_rect->left, src_rect->top, src_rect->right, src_rect->bottom,
339                 dst_rect->left, win_h - dst_rect->top, dst_rect->right, win_h - dst_rect->bottom,
340                 GL_COLOR_BUFFER_BIT, gl_filter);
341         checkGLcall("Swapchain present blit(EXT_framebuffer_blit)\n");
342         LEAVE_GL();
343     }
344     else
345     {
346         struct wined3d_device *device = swapchain->device;
347         struct wined3d_context *context2;
348         float tex_left = src_rect->left;
349         float tex_top = src_rect->top;
350         float tex_right = src_rect->right;
351         float tex_bottom = src_rect->bottom;
352
353         context2 = context_acquire(device, swapchain->back_buffers[0]);
354         context_apply_blit_state(context2, device);
355
356         if (backbuffer->flags & SFLAG_NORMCOORD)
357         {
358             tex_left /= src_w;
359             tex_right /= src_w;
360             tex_top /= src_h;
361             tex_bottom /= src_h;
362         }
363
364         if (is_complex_fixup(backbuffer->resource.format->color_fixup))
365             gl_filter = GL_NEAREST;
366
367         ENTER_GL();
368         context_apply_fbo_state_blit(context2, GL_FRAMEBUFFER, swapchain->front_buffer, NULL, SFLAG_INDRAWABLE);
369
370         /* Set up the texture. The surface is not in a wined3d_texture
371          * container, so there are no D3D texture settings to dirtify. */
372         device->blitter->set_shader(device->blit_priv, context2, backbuffer);
373         glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MIN_FILTER, gl_filter);
374         glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MAG_FILTER, gl_filter);
375
376         context_set_draw_buffer(context, GL_BACK);
377
378         /* Set the viewport to the destination rectandle, disable any projection
379          * transformation set up by context_apply_blit_state(), and draw a
380          * (-1,-1)-(1,1) quad.
381          *
382          * Back up viewport and matrix to avoid breaking last_was_blit
383          *
384          * Note that context_apply_blit_state() set up viewport and ortho to
385          * match the surface size - we want the GL drawable(=window) size. */
386         glPushAttrib(GL_VIEWPORT_BIT);
387         glViewport(dst_rect->left, win_h - dst_rect->bottom, dst_rect->right, win_h - dst_rect->top);
388         glMatrixMode(GL_PROJECTION);
389         glPushMatrix();
390         glLoadIdentity();
391
392         glBegin(GL_QUADS);
393             /* bottom left */
394             glTexCoord2f(tex_left, tex_bottom);
395             glVertex2i(-1, -1);
396
397             /* top left */
398             glTexCoord2f(tex_left, tex_top);
399             glVertex2i(-1, 1);
400
401             /* top right */
402             glTexCoord2f(tex_right, tex_top);
403             glVertex2i(1, 1);
404
405             /* bottom right */
406             glTexCoord2f(tex_right, tex_bottom);
407             glVertex2i(1, -1);
408         glEnd();
409
410         glPopMatrix();
411         glPopAttrib();
412
413         device->blitter->unset_shader(context->gl_info);
414         checkGLcall("Swapchain present blit(manual)\n");
415         LEAVE_GL();
416
417         context_release(context2);
418     }
419 }
420
421 static HRESULT swapchain_gl_present(struct wined3d_swapchain *swapchain, const RECT *src_rect_in,
422         const RECT *dst_rect_in, const RGNDATA *dirty_region, DWORD flags)
423 {
424     const struct wined3d_fb_state *fb = &swapchain->device->fb;
425     const struct wined3d_gl_info *gl_info;
426     struct wined3d_context *context;
427     RECT src_rect, dst_rect;
428     BOOL render_to_fbo;
429
430     context = context_acquire(swapchain->device, swapchain->back_buffers[0]);
431     if (!context->valid)
432     {
433         context_release(context);
434         WARN("Invalid context, skipping present.\n");
435         return WINED3D_OK;
436     }
437
438     gl_info = context->gl_info;
439
440     /* Render the cursor onto the back buffer, using our nifty directdraw blitting code :-) */
441     if (swapchain->device->bCursorVisible &&
442         swapchain->device->cursorTexture &&
443         !swapchain->device->hardwareCursor)
444     {
445         struct wined3d_surface cursor;
446         RECT destRect =
447         {
448             swapchain->device->xScreenSpace - swapchain->device->xHotSpot,
449             swapchain->device->yScreenSpace - swapchain->device->yHotSpot,
450             swapchain->device->xScreenSpace + swapchain->device->cursorWidth - swapchain->device->xHotSpot,
451             swapchain->device->yScreenSpace + swapchain->device->cursorHeight - swapchain->device->yHotSpot,
452         };
453         TRACE("Rendering the cursor. Creating fake surface at %p\n", &cursor);
454         /* Build a fake surface to call the Blitting code. It is not possible to use the interface passed by
455          * the application because we are only supposed to copy the information out. Using a fake surface
456          * allows to use the Blitting engine and avoid copying the whole texture -> render target blitting code.
457          */
458         memset(&cursor, 0, sizeof(cursor));
459         cursor.resource.ref = 1;
460         cursor.resource.device = swapchain->device;
461         cursor.resource.pool = WINED3DPOOL_SCRATCH;
462         cursor.resource.format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
463         cursor.resource.resourceType = WINED3DRTYPE_SURFACE;
464         cursor.texture_name = swapchain->device->cursorTexture;
465         cursor.texture_target = GL_TEXTURE_2D;
466         cursor.texture_level = 0;
467         cursor.resource.width = swapchain->device->cursorWidth;
468         cursor.resource.height = swapchain->device->cursorHeight;
469         /* The cursor must have pow2 sizes */
470         cursor.pow2Width = cursor.resource.width;
471         cursor.pow2Height = cursor.resource.height;
472         /* The surface is in the texture */
473         cursor.flags |= SFLAG_INTEXTURE;
474         /* DDBLT_KEYSRC will cause BltOverride to enable the alpha test with GL_NOTEQUAL, 0.0,
475          * which is exactly what we want :-)
476          */
477         if (swapchain->presentParms.Windowed)
478             MapWindowPoints(NULL, swapchain->win_handle, (LPPOINT)&destRect, 2);
479         wined3d_surface_blt(swapchain->back_buffers[0], &destRect,
480                 &cursor, NULL, WINEDDBLT_KEYSRC, NULL, WINED3DTEXF_POINT);
481     }
482
483     if (swapchain->device->logo_surface)
484     {
485         struct wined3d_surface *src_surface = swapchain->device->logo_surface;
486         RECT rect = {0, 0, src_surface->resource.width, src_surface->resource.height};
487
488         /* Blit the logo into the upper left corner of the drawable. */
489         wined3d_surface_blt(swapchain->back_buffers[0], &rect, src_surface, &rect,
490                  WINEDDBLT_KEYSRC, NULL, WINED3DTEXF_POINT);
491     }
492
493     TRACE("Presenting HDC %p.\n", context->hdc);
494
495     render_to_fbo = swapchain->render_to_fbo;
496
497     if (src_rect_in)
498     {
499         src_rect = *src_rect_in;
500         if (!render_to_fbo && (src_rect.left || src_rect.top
501                 || src_rect.right != swapchain->presentParms.BackBufferWidth
502                 || src_rect.bottom != swapchain->presentParms.BackBufferHeight))
503         {
504             render_to_fbo = TRUE;
505         }
506     }
507     else
508     {
509         src_rect.left = 0;
510         src_rect.top = 0;
511         src_rect.right = swapchain->presentParms.BackBufferWidth;
512         src_rect.bottom = swapchain->presentParms.BackBufferHeight;
513     }
514
515     if (dst_rect_in)
516         dst_rect = *dst_rect_in;
517     else
518         GetClientRect(swapchain->win_handle, &dst_rect);
519
520     if (!render_to_fbo && (dst_rect.left || dst_rect.top
521             || dst_rect.right != swapchain->presentParms.BackBufferWidth
522             || dst_rect.bottom != swapchain->presentParms.BackBufferHeight))
523     {
524         render_to_fbo = TRUE;
525     }
526
527     /* Rendering to a window of different size, presenting partial rectangles,
528      * or rendering to a different window needs help from FBO_blit or a textured
529      * draw. Render the swapchain to a FBO in the future.
530      *
531      * Note that FBO_blit from the backbuffer to the frontbuffer cannot solve
532      * all these issues - this fails if the window is smaller than the backbuffer.
533      */
534     if (!swapchain->render_to_fbo && render_to_fbo && wined3d_settings.offscreen_rendering_mode == ORM_FBO)
535     {
536         surface_load_location(swapchain->back_buffers[0], SFLAG_INTEXTURE, NULL);
537         surface_modify_location(swapchain->back_buffers[0], SFLAG_INDRAWABLE, FALSE);
538         swapchain->render_to_fbo = TRUE;
539         swapchain_update_draw_bindings(swapchain);
540     }
541
542     if (swapchain->render_to_fbo)
543     {
544         /* This codepath should only be hit with the COPY swapeffect. Otherwise a backbuffer-
545          * window size mismatch is impossible(fullscreen) and src and dst rectangles are
546          * not allowed(they need the COPY swapeffect)
547          *
548          * The DISCARD swap effect is ok as well since any backbuffer content is allowed after
549          * the swap. */
550         if (swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP)
551             FIXME("Render-to-fbo with WINED3DSWAPEFFECT_FLIP\n");
552
553         swapchain_blit(swapchain, context, &src_rect, &dst_rect);
554     }
555
556     if (swapchain->num_contexts > 1)
557         wglFinish();
558     SwapBuffers(context->hdc); /* TODO: cycle through the swapchain buffers */
559
560     TRACE("SwapBuffers called, Starting new frame\n");
561     /* FPS support */
562     if (TRACE_ON(fps))
563     {
564         DWORD time = GetTickCount();
565         ++swapchain->frames;
566
567         /* every 1.5 seconds */
568         if (time - swapchain->prev_time > 1500)
569         {
570             TRACE_(fps)("%p @ approx %.2ffps\n",
571                     swapchain, 1000.0 * swapchain->frames / (time - swapchain->prev_time));
572             swapchain->prev_time = time;
573             swapchain->frames = 0;
574         }
575     }
576
577     /* This is disabled, but the code left in for debug purposes.
578      *
579      * Since we're allowed to modify the new back buffer on a D3DSWAPEFFECT_DISCARD flip,
580      * we can clear it with some ugly color to make bad drawing visible and ease debugging.
581      * The Debug runtime does the same on Windows. However, a few games do not redraw the
582      * screen properly, like Max Payne 2, which leaves a few pixels undefined.
583      *
584      * Tests show that the content of the back buffer after a discard flip is indeed not
585      * reliable, so no game can depend on the exact content. However, it resembles the
586      * old contents in some way, for example by showing fragments at other locations. In
587      * general, the color theme is still intact. So Max payne, which draws rather dark scenes
588      * gets a dark background image. If we clear it with a bright ugly color, the game's
589      * bug shows up much more than it does on Windows, and the players see single pixels
590      * with wrong colors.
591      * (The Max Payne bug has been confirmed on Windows with the debug runtime) */
592     if (FALSE && swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD)
593     {
594         static const struct wined3d_color cyan = {0.0f, 1.0f, 1.0f, 1.0f};
595
596         TRACE("Clearing the color buffer with cyan color\n");
597
598         wined3d_device_clear(swapchain->device, 0, NULL,
599                 WINED3DCLEAR_TARGET, &cyan, 1.0f, 0);
600     }
601
602     if (!swapchain->render_to_fbo && ((swapchain->front_buffer->flags & SFLAG_INSYSMEM)
603             || (swapchain->back_buffers[0]->flags & SFLAG_INSYSMEM)))
604     {
605         /* Both memory copies of the surfaces are ok, flip them around too instead of dirtifying
606          * Doesn't work with render_to_fbo because we're not flipping
607          */
608         struct wined3d_surface *front = swapchain->front_buffer;
609         struct wined3d_surface *back = swapchain->back_buffers[0];
610
611         if(front->resource.size == back->resource.size) {
612             DWORD fbflags;
613             flip_surface(front, back);
614
615             /* Tell the front buffer surface that is has been modified. However,
616              * the other locations were preserved during that, so keep the flags.
617              * This serves to update the emulated overlay, if any. */
618             fbflags = front->flags;
619             surface_modify_location(front, SFLAG_INDRAWABLE, TRUE);
620             front->flags = fbflags;
621         }
622         else
623         {
624             surface_modify_location(front, SFLAG_INDRAWABLE, TRUE);
625             surface_modify_location(back, SFLAG_INDRAWABLE, TRUE);
626         }
627     }
628     else
629     {
630         surface_modify_location(swapchain->front_buffer, SFLAG_INDRAWABLE, TRUE);
631         /* If the swapeffect is DISCARD, the back buffer is undefined. That means the SYSMEM
632          * and INTEXTURE copies can keep their old content if they have any defined content.
633          * If the swapeffect is COPY, the content remains the same. If it is FLIP however,
634          * the texture / sysmem copy needs to be reloaded from the drawable
635          */
636         if (swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP)
637             surface_modify_location(swapchain->back_buffers[0], swapchain->back_buffers[0]->draw_binding, TRUE);
638     }
639
640     if (fb->depth_stencil)
641     {
642         if (swapchain->presentParms.Flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
643                 || fb->depth_stencil->flags & SFLAG_DISCARD)
644         {
645             surface_modify_ds_location(fb->depth_stencil, SFLAG_DS_DISCARDED,
646                     fb->depth_stencil->resource.width,
647                     fb->depth_stencil->resource.height);
648             if (fb->depth_stencil == swapchain->device->onscreen_depth_stencil)
649             {
650                 wined3d_surface_decref(swapchain->device->onscreen_depth_stencil);
651                 swapchain->device->onscreen_depth_stencil = NULL;
652             }
653         }
654     }
655
656     context_release(context);
657
658     TRACE("returning\n");
659     return WINED3D_OK;
660 }
661
662 static const struct wined3d_swapchain_ops swapchain_gl_ops =
663 {
664     swapchain_gl_present,
665 };
666
667 /* Helper function that blits the front buffer contents to the target window. */
668 void x11_copy_to_screen(const struct wined3d_swapchain *swapchain, const RECT *rect)
669 {
670     const struct wined3d_surface *front;
671     POINT offset = {0, 0};
672     HDC src_dc, dst_dc;
673     RECT draw_rect;
674     HWND window;
675
676     TRACE("swapchain %p, rect %s.\n", swapchain, wine_dbgstr_rect(rect));
677
678     front = swapchain->front_buffer;
679     if (!(front->resource.usage & WINED3DUSAGE_RENDERTARGET))
680         return;
681
682     if (front->flags & SFLAG_LOCKED)
683         ERR("Trying to blit a mapped surface.\n");
684
685     TRACE("Copying surface %p to screen.\n", front);
686
687     src_dc = front->hDC;
688     window = swapchain->win_handle;
689     dst_dc = GetDCEx(window, 0, DCX_CLIPSIBLINGS | DCX_CACHE);
690
691     /* Front buffer coordinates are screen coordinates. Map them to the
692      * destination window if not fullscreened. */
693     if (swapchain->presentParms.Windowed)
694         ClientToScreen(window, &offset);
695
696     TRACE("offset %s.\n", wine_dbgstr_point(&offset));
697
698     draw_rect.left = 0;
699     draw_rect.right = front->resource.width;
700     draw_rect.top = 0;
701     draw_rect.bottom = front->resource.height;
702
703     if (rect)
704         IntersectRect(&draw_rect, &draw_rect, rect);
705
706     BitBlt(dst_dc, draw_rect.left - offset.x, draw_rect.top - offset.y,
707             draw_rect.right - draw_rect.left, draw_rect.bottom - draw_rect.top,
708             src_dc, draw_rect.left, draw_rect.top, SRCCOPY);
709     ReleaseDC(window, dst_dc);
710 }
711
712 static HRESULT swapchain_gdi_present(struct wined3d_swapchain *swapchain, const RECT *src_rect_in,
713         const RECT *dst_rect_in, const RGNDATA *dirty_region, DWORD flags)
714 {
715     struct wined3d_surface *front, *back;
716
717     if (!swapchain->back_buffers)
718     {
719         WARN("Swapchain doesn't have a backbuffer, returning WINED3DERR_INVALIDCALL\n");
720         return WINED3DERR_INVALIDCALL;
721     }
722     front = swapchain->front_buffer;
723     back = swapchain->back_buffers[0];
724
725     /* Flip the DC. */
726     {
727         HDC tmp;
728         tmp = front->hDC;
729         front->hDC = back->hDC;
730         back->hDC = tmp;
731     }
732
733     /* Flip the DIBsection. */
734     {
735         HBITMAP tmp;
736         tmp = front->dib.DIBsection;
737         front->dib.DIBsection = back->dib.DIBsection;
738         back->dib.DIBsection = tmp;
739     }
740
741     /* Flip the surface data. */
742     {
743         void *tmp;
744
745         tmp = front->dib.bitmap_data;
746         front->dib.bitmap_data = back->dib.bitmap_data;
747         back->dib.bitmap_data = tmp;
748
749         tmp = front->resource.allocatedMemory;
750         front->resource.allocatedMemory = back->resource.allocatedMemory;
751         back->resource.allocatedMemory = tmp;
752
753         if (front->resource.heapMemory)
754             ERR("GDI Surface %p has heap memory allocated.\n", front);
755
756         if (back->resource.heapMemory)
757             ERR("GDI Surface %p has heap memory allocated.\n", back);
758     }
759
760     /* FPS support */
761     if (TRACE_ON(fps))
762     {
763         static LONG prev_time, frames;
764         DWORD time = GetTickCount();
765
766         ++frames;
767
768         /* every 1.5 seconds */
769         if (time - prev_time > 1500)
770         {
771             TRACE_(fps)("@ approx %.2ffps\n", 1000.0 * frames / (time - prev_time));
772             prev_time = time;
773             frames = 0;
774         }
775     }
776
777     x11_copy_to_screen(swapchain, NULL);
778
779     return WINED3D_OK;
780 }
781
782 static const struct wined3d_swapchain_ops swapchain_gdi_ops =
783 {
784     swapchain_gdi_present,
785 };
786
787 void swapchain_update_render_to_fbo(struct wined3d_swapchain *swapchain)
788 {
789     RECT client_rect;
790
791     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
792         return;
793
794     if (!swapchain->presentParms.BackBufferCount)
795     {
796         TRACE("Single buffered rendering.\n");
797         swapchain->render_to_fbo = FALSE;
798         return;
799     }
800
801     GetClientRect(swapchain->win_handle, &client_rect);
802
803     TRACE("Backbuffer %ux%u, window %ux%u.\n",
804             swapchain->presentParms.BackBufferWidth,
805             swapchain->presentParms.BackBufferHeight,
806             client_rect.right, client_rect.bottom);
807     TRACE("Multisample type %#x, quality %#x.\n",
808             swapchain->presentParms.MultiSampleType,
809             swapchain->presentParms.MultiSampleQuality);
810
811     if (!wined3d_settings.always_offscreen && !swapchain->presentParms.MultiSampleType
812             && swapchain->presentParms.BackBufferWidth == client_rect.right
813             && swapchain->presentParms.BackBufferHeight == client_rect.bottom)
814     {
815         TRACE("Backbuffer dimensions match window dimensions, rendering onscreen.\n");
816         swapchain->render_to_fbo = FALSE;
817         return;
818     }
819
820     TRACE("Rendering to FBO.\n");
821     swapchain->render_to_fbo = TRUE;
822 }
823
824 /* Do not call while under the GL lock. */
825 static HRESULT swapchain_init(struct wined3d_swapchain *swapchain, WINED3DSURFTYPE surface_type,
826         struct wined3d_device *device, WINED3DPRESENT_PARAMETERS *present_parameters,
827         void *parent, const struct wined3d_parent_ops *parent_ops)
828 {
829     const struct wined3d_adapter *adapter = device->adapter;
830     const struct wined3d_format *format;
831     BOOL displaymode_set = FALSE;
832     WINED3DDISPLAYMODE mode;
833     RECT client_rect;
834     HWND window;
835     HRESULT hr;
836     UINT i;
837
838     if (present_parameters->BackBufferCount > WINED3DPRESENT_BACK_BUFFER_MAX)
839     {
840         FIXME("The application requested %u back buffers, this is not supported.\n",
841                 present_parameters->BackBufferCount);
842         return WINED3DERR_INVALIDCALL;
843     }
844
845     if (present_parameters->BackBufferCount > 1)
846     {
847         FIXME("The application requested more than one back buffer, this is not properly supported.\n"
848                 "Please configure the application to use double buffering (1 back buffer) if possible.\n");
849     }
850
851     switch (surface_type)
852     {
853         case SURFACE_GDI:
854             swapchain->swapchain_ops = &swapchain_gdi_ops;
855             break;
856
857         case SURFACE_OPENGL:
858             swapchain->swapchain_ops = &swapchain_gl_ops;
859             break;
860
861         default:
862             ERR("Invalid surface type %#x.\n", surface_type);
863             return WINED3DERR_INVALIDCALL;
864     }
865
866     window = present_parameters->hDeviceWindow ? present_parameters->hDeviceWindow : device->createParms.hFocusWindow;
867
868     swapchain->device = device;
869     swapchain->parent = parent;
870     swapchain->parent_ops = parent_ops;
871     swapchain->ref = 1;
872     swapchain->win_handle = window;
873     swapchain->device_window = window;
874
875     wined3d_get_adapter_display_mode(device->wined3d, adapter->ordinal, &mode);
876     swapchain->orig_width = mode.Width;
877     swapchain->orig_height = mode.Height;
878     swapchain->orig_fmt = mode.Format;
879     format = wined3d_get_format(&adapter->gl_info, mode.Format);
880
881     GetClientRect(window, &client_rect);
882     if (present_parameters->Windowed
883             && (!present_parameters->BackBufferWidth || !present_parameters->BackBufferHeight
884             || present_parameters->BackBufferFormat == WINED3DFMT_UNKNOWN))
885     {
886
887         if (!present_parameters->BackBufferWidth)
888         {
889             present_parameters->BackBufferWidth = client_rect.right;
890             TRACE("Updating width to %u.\n", present_parameters->BackBufferWidth);
891         }
892
893         if (!present_parameters->BackBufferHeight)
894         {
895             present_parameters->BackBufferHeight = client_rect.bottom;
896             TRACE("Updating height to %u.\n", present_parameters->BackBufferHeight);
897         }
898
899         if (present_parameters->BackBufferFormat == WINED3DFMT_UNKNOWN)
900         {
901             present_parameters->BackBufferFormat = swapchain->orig_fmt;
902             TRACE("Updating format to %s.\n", debug_d3dformat(swapchain->orig_fmt));
903         }
904     }
905     swapchain->presentParms = *present_parameters;
906     swapchain_update_render_to_fbo(swapchain);
907
908     TRACE("Creating front buffer.\n");
909     hr = device->device_parent->ops->create_rendertarget(device->device_parent, parent,
910             swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
911             swapchain->presentParms.BackBufferFormat, swapchain->presentParms.MultiSampleType,
912             swapchain->presentParms.MultiSampleQuality, TRUE /* Lockable */,
913             &swapchain->front_buffer);
914     if (FAILED(hr))
915     {
916         WARN("Failed to create front buffer, hr %#x.\n", hr);
917         goto err;
918     }
919
920     surface_set_container(swapchain->front_buffer, WINED3D_CONTAINER_SWAPCHAIN, swapchain);
921     if (surface_type == SURFACE_OPENGL)
922     {
923         surface_modify_location(swapchain->front_buffer, SFLAG_INDRAWABLE, TRUE);
924     }
925
926     /* MSDN says we're only allowed a single fullscreen swapchain per device,
927      * so we should really check to see if there is a fullscreen swapchain
928      * already. Does a single head count as full screen? */
929
930     if (!present_parameters->Windowed)
931     {
932         WINED3DDISPLAYMODE mode;
933
934         /* Change the display settings */
935         mode.Width = present_parameters->BackBufferWidth;
936         mode.Height = present_parameters->BackBufferHeight;
937         mode.Format = present_parameters->BackBufferFormat;
938         mode.RefreshRate = present_parameters->FullScreen_RefreshRateInHz;
939
940         hr = wined3d_device_set_display_mode(device, 0, &mode);
941         if (FAILED(hr))
942         {
943             WARN("Failed to set display mode, hr %#x.\n", hr);
944             goto err;
945         }
946         displaymode_set = TRUE;
947     }
948
949     if (surface_type == SURFACE_OPENGL)
950     {
951         static const enum wined3d_format_id formats[] =
952         {
953             WINED3DFMT_D24_UNORM_S8_UINT,
954             WINED3DFMT_D32_UNORM,
955             WINED3DFMT_R24_UNORM_X8_TYPELESS,
956             WINED3DFMT_D16_UNORM,
957             WINED3DFMT_S1_UINT_D15_UNORM
958         };
959
960         const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
961
962         swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(*swapchain->context));
963         if (!swapchain->context)
964         {
965             ERR("Failed to create the context array.\n");
966             hr = E_OUTOFMEMORY;
967             goto err;
968         }
969         swapchain->num_contexts = 1;
970
971         /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
972          * You are able to add a depth + stencil surface at a later stage when you need it.
973          * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
974          * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
975          * context, need torecreate shaders, textures and other resources.
976          *
977          * The context manager already takes care of the state problem and for the other tasks code from Reset
978          * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
979          * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
980          * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
981          * issue needs to be fixed. */
982         for (i = 0; i < (sizeof(formats) / sizeof(*formats)); i++)
983         {
984             swapchain->ds_format = wined3d_get_format(gl_info, formats[i]);
985             swapchain->context[0] = context_create(swapchain, swapchain->front_buffer, swapchain->ds_format);
986             if (swapchain->context[0]) break;
987             TRACE("Depth stencil format %s is not supported, trying next format\n",
988                   debug_d3dformat(formats[i]));
989         }
990
991         if (!swapchain->context[0])
992         {
993             WARN("Failed to create context.\n");
994             hr = WINED3DERR_NOTAVAILABLE;
995             goto err;
996         }
997
998         if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
999                 && (!present_parameters->EnableAutoDepthStencil
1000                 || swapchain->presentParms.AutoDepthStencilFormat != swapchain->ds_format->id))
1001         {
1002             FIXME("Add OpenGL context recreation support to context_validate_onscreen_formats\n");
1003         }
1004         context_release(swapchain->context[0]);
1005     }
1006
1007     if (swapchain->presentParms.BackBufferCount > 0)
1008     {
1009         swapchain->back_buffers = HeapAlloc(GetProcessHeap(), 0,
1010                 sizeof(*swapchain->back_buffers) * swapchain->presentParms.BackBufferCount);
1011         if (!swapchain->back_buffers)
1012         {
1013             ERR("Failed to allocate backbuffer array memory.\n");
1014             hr = E_OUTOFMEMORY;
1015             goto err;
1016         }
1017
1018         for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
1019         {
1020             TRACE("Creating back buffer %u.\n", i);
1021             hr = device->device_parent->ops->create_rendertarget(device->device_parent, parent,
1022                     swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
1023                     swapchain->presentParms.BackBufferFormat, swapchain->presentParms.MultiSampleType,
1024                     swapchain->presentParms.MultiSampleQuality, TRUE /* Lockable */,
1025                     &swapchain->back_buffers[i]);
1026             if (FAILED(hr))
1027             {
1028                 WARN("Failed to create back buffer %u, hr %#x.\n", i, hr);
1029                 goto err;
1030             }
1031
1032             surface_set_container(swapchain->back_buffers[i], WINED3D_CONTAINER_SWAPCHAIN, swapchain);
1033         }
1034     }
1035
1036     /* Swapchains share the depth/stencil buffer, so only create a single depthstencil surface. */
1037     if (present_parameters->EnableAutoDepthStencil && surface_type == SURFACE_OPENGL)
1038     {
1039         TRACE("Creating depth/stencil buffer.\n");
1040         if (!device->auto_depth_stencil)
1041         {
1042             hr = device->device_parent->ops->create_depth_stencil(device->device_parent,
1043                     swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
1044                     swapchain->presentParms.AutoDepthStencilFormat, swapchain->presentParms.MultiSampleType,
1045                     swapchain->presentParms.MultiSampleQuality, FALSE /* FIXME: Discard */,
1046                     &device->auto_depth_stencil);
1047             if (FAILED(hr))
1048             {
1049                 WARN("Failed to create the auto depth stencil, hr %#x.\n", hr);
1050                 goto err;
1051             }
1052
1053             surface_set_container(device->auto_depth_stencil, WINED3D_CONTAINER_NONE, NULL);
1054         }
1055     }
1056
1057     wined3d_swapchain_get_gamma_ramp(swapchain, &swapchain->orig_gamma);
1058
1059     return WINED3D_OK;
1060
1061 err:
1062     if (displaymode_set)
1063     {
1064         DEVMODEW devmode;
1065
1066         ClipCursor(NULL);
1067
1068         /* Change the display settings */
1069         memset(&devmode, 0, sizeof(devmode));
1070         devmode.dmSize = sizeof(devmode);
1071         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1072         devmode.dmBitsPerPel = format->byte_count * CHAR_BIT;
1073         devmode.dmPelsWidth = swapchain->orig_width;
1074         devmode.dmPelsHeight = swapchain->orig_height;
1075         ChangeDisplaySettingsExW(adapter->DeviceName, &devmode, NULL, CDS_FULLSCREEN, NULL);
1076     }
1077
1078     if (swapchain->back_buffers)
1079     {
1080         for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
1081         {
1082             if (swapchain->back_buffers[i])
1083             {
1084                 surface_set_container(swapchain->back_buffers[i], WINED3D_CONTAINER_NONE, NULL);
1085                 wined3d_surface_decref(swapchain->back_buffers[i]);
1086             }
1087         }
1088         HeapFree(GetProcessHeap(), 0, swapchain->back_buffers);
1089     }
1090
1091     if (swapchain->context)
1092     {
1093         if (swapchain->context[0])
1094         {
1095             context_release(swapchain->context[0]);
1096             context_destroy(device, swapchain->context[0]);
1097             swapchain->num_contexts = 0;
1098         }
1099         HeapFree(GetProcessHeap(), 0, swapchain->context);
1100     }
1101
1102     if (swapchain->front_buffer)
1103     {
1104         surface_set_container(swapchain->front_buffer, WINED3D_CONTAINER_NONE, NULL);
1105         wined3d_surface_decref(swapchain->front_buffer);
1106     }
1107
1108     return hr;
1109 }
1110
1111 /* Do not call while under the GL lock. */
1112 HRESULT CDECL wined3d_swapchain_create(struct wined3d_device *device,
1113         WINED3DPRESENT_PARAMETERS *present_parameters, WINED3DSURFTYPE surface_type,
1114         void *parent, const struct wined3d_parent_ops *parent_ops,
1115         struct wined3d_swapchain **swapchain)
1116 {
1117     struct wined3d_swapchain *object;
1118     HRESULT hr;
1119
1120     TRACE("device %p, present_parameters %p, swapchain %p, parent %p, surface_type %#x.\n",
1121             device, present_parameters, swapchain, parent, surface_type);
1122
1123     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1124     if (!object)
1125     {
1126         ERR("Failed to allocate swapchain memory.\n");
1127         return E_OUTOFMEMORY;
1128     }
1129
1130     hr = swapchain_init(object, surface_type, device, present_parameters, parent, parent_ops);
1131     if (FAILED(hr))
1132     {
1133         WARN("Failed to initialize swapchain, hr %#x.\n", hr);
1134         HeapFree(GetProcessHeap(), 0, object);
1135         return hr;
1136     }
1137
1138     TRACE("Created swapchain %p.\n", object);
1139     *swapchain = object;
1140
1141     return WINED3D_OK;
1142 }
1143
1144 /* Do not call while under the GL lock. */
1145 static struct wined3d_context *swapchain_create_context(struct wined3d_swapchain *swapchain)
1146 {
1147     struct wined3d_context **newArray;
1148     struct wined3d_context *ctx;
1149
1150     TRACE("Creating a new context for swapchain %p, thread %u.\n", swapchain, GetCurrentThreadId());
1151
1152     if (!(ctx = context_create(swapchain, swapchain->front_buffer, swapchain->ds_format)))
1153     {
1154         ERR("Failed to create a new context for the swapchain\n");
1155         return NULL;
1156     }
1157     context_release(ctx);
1158
1159     newArray = HeapAlloc(GetProcessHeap(), 0, sizeof(*newArray) * (swapchain->num_contexts + 1));
1160     if(!newArray) {
1161         ERR("Out of memory when trying to allocate a new context array\n");
1162         context_destroy(swapchain->device, ctx);
1163         return NULL;
1164     }
1165     memcpy(newArray, swapchain->context, sizeof(*newArray) * swapchain->num_contexts);
1166     HeapFree(GetProcessHeap(), 0, swapchain->context);
1167     newArray[swapchain->num_contexts] = ctx;
1168     swapchain->context = newArray;
1169     swapchain->num_contexts++;
1170
1171     TRACE("Returning context %p\n", ctx);
1172     return ctx;
1173 }
1174
1175 void swapchain_destroy_contexts(struct wined3d_swapchain *swapchain)
1176 {
1177     unsigned int i;
1178
1179     for (i = 0; i < swapchain->num_contexts; ++i)
1180     {
1181         context_destroy(swapchain->device, swapchain->context[i]);
1182     }
1183     swapchain->num_contexts = 0;
1184 }
1185
1186 struct wined3d_context *swapchain_get_context(struct wined3d_swapchain *swapchain)
1187 {
1188     DWORD tid = GetCurrentThreadId();
1189     unsigned int i;
1190
1191     for (i = 0; i < swapchain->num_contexts; ++i)
1192     {
1193         if (swapchain->context[i]->tid == tid)
1194             return swapchain->context[i];
1195     }
1196
1197     /* Create a new context for the thread */
1198     return swapchain_create_context(swapchain);
1199 }
1200
1201 void get_drawable_size_swapchain(const struct wined3d_context *context, UINT *width, UINT *height)
1202 {
1203     /* The drawable size of an onscreen drawable is the surface size.
1204      * (Actually: The window size, but the surface is created in window size) */
1205     *width = context->current_rt->resource.width;
1206     *height = context->current_rt->resource.height;
1207 }
1208
1209 HDC swapchain_get_backup_dc(struct wined3d_swapchain *swapchain)
1210 {
1211     if (!swapchain->backup_dc)
1212     {
1213         TRACE("Creating the backup window for swapchain %p.\n", swapchain);
1214
1215         if (!(swapchain->backup_wnd = CreateWindowA(WINED3D_OPENGL_WINDOW_CLASS_NAME, "WineD3D fake window",
1216                 WS_OVERLAPPEDWINDOW, 10, 10, 10, 10, NULL, NULL, NULL, NULL)))
1217         {
1218             ERR("Failed to create a window.\n");
1219             return NULL;
1220         }
1221
1222         if (!(swapchain->backup_dc = GetDC(swapchain->backup_wnd)))
1223         {
1224             ERR("Failed to get a DC.\n");
1225             DestroyWindow(swapchain->backup_wnd);
1226             swapchain->backup_wnd = NULL;
1227             return NULL;
1228         }
1229     }
1230
1231     return swapchain->backup_dc;
1232 }
1233
1234 void swapchain_update_draw_bindings(struct wined3d_swapchain *swapchain)
1235 {
1236     UINT i;
1237
1238     surface_update_draw_binding(swapchain->front_buffer);
1239
1240     for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
1241     {
1242         surface_update_draw_binding(swapchain->back_buffers[i]);
1243     }
1244 }