wined3d: Implement WINED3DSIH_UTOF in the GLSL shader backend.
[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 "wine/port.h"
25 #include "wined3d_private.h"
26
27 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
28 WINE_DECLARE_DEBUG_CHANNEL(fps);
29
30 /* Do not call while under the GL lock. */
31 static void swapchain_cleanup(struct wined3d_swapchain *swapchain)
32 {
33     struct wined3d_display_mode mode;
34     HRESULT hr;
35     UINT i;
36
37     TRACE("Destroying swapchain %p.\n", swapchain);
38
39     wined3d_swapchain_set_gamma_ramp(swapchain, 0, &swapchain->orig_gamma);
40
41     /* Release the swapchain's draw buffers. Make sure swapchain->back_buffers[0]
42      * is the last buffer to be destroyed, FindContext() depends on that. */
43     if (swapchain->front_buffer)
44     {
45         if (swapchain->front_buffer->container.type == WINED3D_CONTAINER_SWAPCHAIN)
46             surface_set_container(swapchain->front_buffer, WINED3D_CONTAINER_NONE, NULL);
47         if (wined3d_surface_decref(swapchain->front_buffer))
48             WARN("Something's still holding the front buffer (%p).\n", swapchain->front_buffer);
49         swapchain->front_buffer = NULL;
50     }
51
52     if (swapchain->back_buffers)
53     {
54         i = swapchain->desc.backbuffer_count;
55
56         while (i--)
57         {
58             if (swapchain->back_buffers[i]->container.type == WINED3D_CONTAINER_SWAPCHAIN)
59                 surface_set_container(swapchain->back_buffers[i], WINED3D_CONTAINER_NONE, NULL);
60             if (wined3d_surface_decref(swapchain->back_buffers[i]))
61                 WARN("Something's still holding back buffer %u (%p).\n", i, swapchain->back_buffers[i]);
62         }
63         HeapFree(GetProcessHeap(), 0, swapchain->back_buffers);
64         swapchain->back_buffers = NULL;
65     }
66
67     for (i = 0; i < swapchain->num_contexts; ++i)
68     {
69         context_destroy(swapchain->device, swapchain->context[i]);
70     }
71     HeapFree(GetProcessHeap(), 0, swapchain->context);
72
73     /* Restore the screen resolution if we rendered in fullscreen.
74      * This will restore the screen resolution to what it was before creating
75      * the swapchain. In case of d3d8 and d3d9 this will be the original
76      * desktop resolution. In case of d3d7 this will be a NOP because ddraw
77      * sets the resolution before starting up Direct3D, thus orig_width and
78      * orig_height will be equal to the modes in the presentation params. */
79     if (!swapchain->desc.windowed && swapchain->desc.auto_restore_display_mode)
80     {
81         mode.width = swapchain->orig_width;
82         mode.height = swapchain->orig_height;
83         mode.refresh_rate = 0;
84         mode.format_id = swapchain->orig_fmt;
85         mode.scanline_ordering = WINED3D_SCANLINE_ORDERING_UNKNOWN;
86         if (FAILED(hr = wined3d_set_adapter_display_mode(swapchain->device->wined3d,
87                 swapchain->device->adapter->ordinal, &mode)))
88             ERR("Failed to restore display mode, hr %#x.\n", hr);
89     }
90
91     if (swapchain->backup_dc)
92     {
93         TRACE("Destroying backup wined3d window %p, dc %p.\n", swapchain->backup_wnd, swapchain->backup_dc);
94
95         ReleaseDC(swapchain->backup_wnd, swapchain->backup_dc);
96         DestroyWindow(swapchain->backup_wnd);
97     }
98 }
99
100 ULONG CDECL wined3d_swapchain_incref(struct wined3d_swapchain *swapchain)
101 {
102     ULONG refcount = InterlockedIncrement(&swapchain->ref);
103
104     TRACE("%p increasing refcount to %u.\n", swapchain, refcount);
105
106     return refcount;
107 }
108
109 /* Do not call while under the GL lock. */
110 ULONG CDECL wined3d_swapchain_decref(struct wined3d_swapchain *swapchain)
111 {
112     ULONG refcount = InterlockedDecrement(&swapchain->ref);
113
114     TRACE("%p decreasing refcount to %u.\n", swapchain, refcount);
115
116     if (!refcount)
117     {
118         swapchain_cleanup(swapchain);
119         swapchain->parent_ops->wined3d_object_destroyed(swapchain->parent);
120         HeapFree(GetProcessHeap(), 0, swapchain);
121     }
122
123     return refcount;
124 }
125
126 void * CDECL wined3d_swapchain_get_parent(const struct wined3d_swapchain *swapchain)
127 {
128     TRACE("swapchain %p.\n", swapchain);
129
130     return swapchain->parent;
131 }
132
133 void CDECL wined3d_swapchain_set_window(struct wined3d_swapchain *swapchain, HWND window)
134 {
135     if (!window)
136         window = swapchain->device_window;
137     if (window == swapchain->win_handle)
138         return;
139
140     TRACE("Setting swapchain %p window from %p to %p.\n",
141             swapchain, swapchain->win_handle, window);
142     swapchain->win_handle = window;
143 }
144
145 HRESULT CDECL wined3d_swapchain_present(struct wined3d_swapchain *swapchain,
146         const RECT *src_rect, const RECT *dst_rect, HWND dst_window_override,
147         const RGNDATA *dirty_region, DWORD flags)
148 {
149     TRACE("swapchain %p, src_rect %s, dst_rect %s, dst_window_override %p, dirty_region %p, flags %#x.\n",
150             swapchain, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect),
151             dst_window_override, dirty_region, flags);
152
153     if (flags)
154         FIXME("Ignoring flags %#x.\n", flags);
155
156     if (!swapchain->back_buffers)
157     {
158         WARN("Swapchain doesn't have a backbuffer, returning WINED3DERR_INVALIDCALL\n");
159         return WINED3DERR_INVALIDCALL;
160     }
161
162     wined3d_swapchain_set_window(swapchain, dst_window_override);
163
164     swapchain->swapchain_ops->swapchain_present(swapchain, src_rect, dst_rect, dirty_region, flags);
165
166     return WINED3D_OK;
167 }
168
169 HRESULT CDECL wined3d_swapchain_get_front_buffer_data(const struct wined3d_swapchain *swapchain,
170         struct wined3d_surface *dst_surface)
171 {
172     struct wined3d_surface *src_surface;
173     RECT src_rect, dst_rect;
174
175     TRACE("swapchain %p, dst_surface %p.\n", swapchain, dst_surface);
176
177     src_surface = swapchain->front_buffer;
178     SetRect(&src_rect, 0, 0, src_surface->resource.width, src_surface->resource.height);
179     dst_rect = src_rect;
180
181     if (swapchain->desc.windowed)
182     {
183         MapWindowPoints(swapchain->win_handle, NULL, (POINT *)&dst_rect, 2);
184         FIXME("Using destination rect %s in windowed mode, this is likely wrong.\n",
185                 wine_dbgstr_rect(&dst_rect));
186     }
187
188     return wined3d_surface_blt(dst_surface, &dst_rect, src_surface, &src_rect, 0, NULL, WINED3D_TEXF_POINT);
189 }
190
191 struct wined3d_surface * CDECL wined3d_swapchain_get_back_buffer(const struct wined3d_swapchain *swapchain,
192         UINT back_buffer_idx, enum wined3d_backbuffer_type type)
193 {
194     TRACE("swapchain %p, back_buffer_idx %u, type %#x.\n",
195             swapchain, back_buffer_idx, type);
196
197     /* Return invalid if there is no backbuffer array, otherwise it will
198      * crash when ddraw is used (there swapchain->back_buffers is always
199      * NULL). We need this because this function is called from
200      * stateblock_init_default_state() to get the default scissorrect
201      * dimensions. */
202     if (!swapchain->back_buffers || back_buffer_idx >= swapchain->desc.backbuffer_count)
203     {
204         WARN("Invalid back buffer index.\n");
205         /* Native d3d9 doesn't set NULL here, just as wine's d3d9. But set it
206          * here in wined3d to avoid problems in other libs. */
207         return NULL;
208     }
209
210     TRACE("Returning back buffer %p.\n", swapchain->back_buffers[back_buffer_idx]);
211
212     return swapchain->back_buffers[back_buffer_idx];
213 }
214
215 HRESULT CDECL wined3d_swapchain_get_raster_status(const struct wined3d_swapchain *swapchain,
216         struct wined3d_raster_status *raster_status)
217 {
218     TRACE("swapchain %p, raster_status %p.\n", swapchain, raster_status);
219
220     return wined3d_get_adapter_raster_status(swapchain->device->wined3d,
221             swapchain->device->adapter->ordinal, raster_status);
222 }
223
224 HRESULT CDECL wined3d_swapchain_get_display_mode(const struct wined3d_swapchain *swapchain,
225         struct wined3d_display_mode *mode, enum wined3d_display_rotation *rotation)
226 {
227     HRESULT hr;
228
229     TRACE("swapchain %p, mode %p, rotation %p.\n", swapchain, mode, rotation);
230
231     hr = wined3d_get_adapter_display_mode(swapchain->device->wined3d,
232             swapchain->device->adapter->ordinal, mode, rotation);
233
234     TRACE("Returning w %u, h %u, refresh rate %u, format %s.\n",
235             mode->width, mode->height, mode->refresh_rate, debug_d3dformat(mode->format_id));
236
237     return hr;
238 }
239
240 struct wined3d_device * CDECL wined3d_swapchain_get_device(const struct wined3d_swapchain *swapchain)
241 {
242     TRACE("swapchain %p.\n", swapchain);
243
244     return swapchain->device;
245 }
246
247 void CDECL wined3d_swapchain_get_desc(const struct wined3d_swapchain *swapchain,
248         struct wined3d_swapchain_desc *desc)
249 {
250     TRACE("swapchain %p, desc %p.\n", swapchain, desc);
251
252     *desc = swapchain->desc;
253 }
254
255 HRESULT CDECL wined3d_swapchain_set_gamma_ramp(const struct wined3d_swapchain *swapchain,
256         DWORD flags, const struct wined3d_gamma_ramp *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         struct wined3d_gamma_ramp *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         gl_info->gl_ops.gl.p_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         gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
329         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
330         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
331         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
332         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
333
334         gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
335         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_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         gl_info->gl_ops.gl.p_glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MIN_FILTER, gl_filter);
374         gl_info->gl_ops.gl.p_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         gl_info->gl_ops.gl.p_glPushAttrib(GL_VIEWPORT_BIT);
387         gl_info->gl_ops.gl.p_glViewport(dst_rect->left, win_h - dst_rect->bottom,
388                 dst_rect->right, win_h - dst_rect->top);
389         gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
390         gl_info->gl_ops.gl.p_glPushMatrix();
391         gl_info->gl_ops.gl.p_glLoadIdentity();
392
393         gl_info->gl_ops.gl.p_glBegin(GL_QUADS);
394             /* bottom left */
395             gl_info->gl_ops.gl.p_glTexCoord2f(tex_left, tex_bottom);
396             gl_info->gl_ops.gl.p_glVertex2i(-1, -1);
397
398             /* top left */
399             gl_info->gl_ops.gl.p_glTexCoord2f(tex_left, tex_top);
400             gl_info->gl_ops.gl.p_glVertex2i(-1, 1);
401
402             /* top right */
403             gl_info->gl_ops.gl.p_glTexCoord2f(tex_right, tex_top);
404             gl_info->gl_ops.gl.p_glVertex2i(1, 1);
405
406             /* bottom right */
407             gl_info->gl_ops.gl.p_glTexCoord2f(tex_right, tex_bottom);
408             gl_info->gl_ops.gl.p_glVertex2i(1, -1);
409         gl_info->gl_ops.gl.p_glEnd();
410
411         gl_info->gl_ops.gl.p_glPopMatrix();
412         gl_info->gl_ops.gl.p_glPopAttrib();
413
414         device->blitter->unset_shader(context->gl_info);
415         checkGLcall("Swapchain present blit(manual)\n");
416         LEAVE_GL();
417
418         context_release(context2);
419     }
420 }
421
422 static void swapchain_gl_present(struct wined3d_swapchain *swapchain, const RECT *src_rect_in,
423         const RECT *dst_rect_in, const RGNDATA *dirty_region, DWORD flags)
424 {
425     struct wined3d_surface *back_buffer = swapchain->back_buffers[0];
426     const struct wined3d_fb_state *fb = &swapchain->device->fb;
427     const struct wined3d_gl_info *gl_info;
428     struct wined3d_context *context;
429     RECT src_rect, dst_rect;
430     BOOL render_to_fbo;
431
432     context = context_acquire(swapchain->device, back_buffer);
433     if (!context->valid)
434     {
435         context_release(context);
436         WARN("Invalid context, skipping present.\n");
437         return;
438     }
439
440     gl_info = context->gl_info;
441
442     /* Render the cursor onto the back buffer, using our nifty directdraw blitting code :-) */
443     if (swapchain->device->bCursorVisible &&
444         swapchain->device->cursorTexture &&
445         !swapchain->device->hardwareCursor)
446     {
447         struct wined3d_surface cursor;
448         RECT destRect =
449         {
450             swapchain->device->xScreenSpace - swapchain->device->xHotSpot,
451             swapchain->device->yScreenSpace - swapchain->device->yHotSpot,
452             swapchain->device->xScreenSpace + swapchain->device->cursorWidth - swapchain->device->xHotSpot,
453             swapchain->device->yScreenSpace + swapchain->device->cursorHeight - swapchain->device->yHotSpot,
454         };
455         TRACE("Rendering the cursor. Creating fake surface at %p\n", &cursor);
456         /* Build a fake surface to call the Blitting code. It is not possible to use the interface passed by
457          * the application because we are only supposed to copy the information out. Using a fake surface
458          * allows us to use the Blitting engine and avoid copying the whole texture -> render target blitting code.
459          */
460         memset(&cursor, 0, sizeof(cursor));
461         cursor.resource.ref = 1;
462         cursor.resource.device = swapchain->device;
463         cursor.resource.pool = WINED3D_POOL_SCRATCH;
464         cursor.resource.format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
465         cursor.resource.type = WINED3D_RTYPE_SURFACE;
466         cursor.texture_name = swapchain->device->cursorTexture;
467         cursor.texture_target = GL_TEXTURE_2D;
468         cursor.texture_level = 0;
469         cursor.resource.width = swapchain->device->cursorWidth;
470         cursor.resource.height = swapchain->device->cursorHeight;
471         /* The cursor must have pow2 sizes */
472         cursor.pow2Width = cursor.resource.width;
473         cursor.pow2Height = cursor.resource.height;
474         /* The surface is in the texture */
475         cursor.flags |= SFLAG_INTEXTURE;
476         /* DDBLT_KEYSRC will cause BltOverride to enable the alpha test with GL_NOTEQUAL, 0.0,
477          * which is exactly what we want :-)
478          */
479         if (swapchain->desc.windowed)
480             MapWindowPoints(NULL, swapchain->win_handle, (POINT *)&destRect, 2);
481         wined3d_surface_blt(back_buffer, &destRect, &cursor, NULL, WINEDDBLT_KEYSRC,
482                 NULL, WINED3D_TEXF_POINT);
483     }
484
485     if (swapchain->device->logo_surface)
486     {
487         struct wined3d_surface *src_surface = swapchain->device->logo_surface;
488         RECT rect = {0, 0, src_surface->resource.width, src_surface->resource.height};
489
490         /* Blit the logo into the upper left corner of the drawable. */
491         wined3d_surface_blt(back_buffer, &rect, src_surface, &rect, WINEDDBLT_KEYSRC,
492                 NULL, WINED3D_TEXF_POINT);
493     }
494
495     TRACE("Presenting HDC %p.\n", context->hdc);
496
497     render_to_fbo = swapchain->render_to_fbo;
498
499     if (src_rect_in)
500     {
501         src_rect = *src_rect_in;
502         if (!render_to_fbo && (src_rect.left || src_rect.top
503                 || src_rect.right != swapchain->desc.backbuffer_width
504                 || src_rect.bottom != swapchain->desc.backbuffer_height))
505         {
506             render_to_fbo = TRUE;
507         }
508     }
509     else
510     {
511         src_rect.left = 0;
512         src_rect.top = 0;
513         src_rect.right = swapchain->desc.backbuffer_width;
514         src_rect.bottom = swapchain->desc.backbuffer_height;
515     }
516
517     if (dst_rect_in)
518         dst_rect = *dst_rect_in;
519     else
520         GetClientRect(swapchain->win_handle, &dst_rect);
521
522     if (!render_to_fbo && (dst_rect.left || dst_rect.top
523             || dst_rect.right != swapchain->desc.backbuffer_width
524             || dst_rect.bottom != swapchain->desc.backbuffer_height))
525         render_to_fbo = TRUE;
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(back_buffer, SFLAG_INTEXTURE, NULL);
537         surface_modify_location(back_buffer, SFLAG_INDRAWABLE, FALSE);
538         swapchain->render_to_fbo = TRUE;
539         swapchain_update_draw_bindings(swapchain);
540     }
541     else
542     {
543         surface_load_location(back_buffer, back_buffer->draw_binding, NULL);
544     }
545
546     if (swapchain->render_to_fbo)
547     {
548         /* This codepath should only be hit with the COPY swapeffect. Otherwise a backbuffer-
549          * window size mismatch is impossible(fullscreen) and src and dst rectangles are
550          * not allowed(they need the COPY swapeffect)
551          *
552          * The DISCARD swap effect is ok as well since any backbuffer content is allowed after
553          * the swap. */
554         if (swapchain->desc.swap_effect == WINED3D_SWAP_EFFECT_FLIP)
555             FIXME("Render-to-fbo with WINED3D_SWAP_EFFECT_FLIP\n");
556
557         swapchain_blit(swapchain, context, &src_rect, &dst_rect);
558     }
559
560     if (swapchain->num_contexts > 1)
561         gl_info->gl_ops.gl.p_glFinish();
562     SwapBuffers(context->hdc); /* TODO: cycle through the swapchain buffers */
563
564     TRACE("SwapBuffers called, Starting new frame\n");
565     /* FPS support */
566     if (TRACE_ON(fps))
567     {
568         DWORD time = GetTickCount();
569         ++swapchain->frames;
570
571         /* every 1.5 seconds */
572         if (time - swapchain->prev_time > 1500)
573         {
574             TRACE_(fps)("%p @ approx %.2ffps\n",
575                     swapchain, 1000.0 * swapchain->frames / (time - swapchain->prev_time));
576             swapchain->prev_time = time;
577             swapchain->frames = 0;
578         }
579     }
580
581     /* This is disabled, but the code left in for debug purposes.
582      *
583      * Since we're allowed to modify the new back buffer on a D3DSWAPEFFECT_DISCARD flip,
584      * we can clear it with some ugly color to make bad drawing visible and ease debugging.
585      * The Debug runtime does the same on Windows. However, a few games do not redraw the
586      * screen properly, like Max Payne 2, which leaves a few pixels undefined.
587      *
588      * Tests show that the content of the back buffer after a discard flip is indeed not
589      * reliable, so no game can depend on the exact content. However, it resembles the
590      * old contents in some way, for example by showing fragments at other locations. In
591      * general, the color theme is still intact. So Max payne, which draws rather dark scenes
592      * gets a dark background image. If we clear it with a bright ugly color, the game's
593      * bug shows up much more than it does on Windows, and the players see single pixels
594      * with wrong colors.
595      * (The Max Payne bug has been confirmed on Windows with the debug runtime) */
596     if (FALSE && swapchain->desc.swap_effect == WINED3D_SWAP_EFFECT_DISCARD)
597     {
598         static const struct wined3d_color cyan = {0.0f, 1.0f, 1.0f, 1.0f};
599
600         TRACE("Clearing the color buffer with cyan color\n");
601
602         wined3d_device_clear(swapchain->device, 0, NULL,
603                 WINED3DCLEAR_TARGET, &cyan, 1.0f, 0);
604     }
605
606     if (!swapchain->render_to_fbo && ((swapchain->front_buffer->flags & SFLAG_INSYSMEM)
607             || (back_buffer->flags & SFLAG_INSYSMEM)))
608     {
609         /* Both memory copies of the surfaces are ok, flip them around too instead of dirtifying
610          * Doesn't work with render_to_fbo because we're not flipping
611          */
612         struct wined3d_surface *front = swapchain->front_buffer;
613
614         if (front->resource.size == back_buffer->resource.size)
615         {
616             DWORD fbflags;
617             flip_surface(front, back_buffer);
618
619             /* Tell the front buffer surface that is has been modified. However,
620              * the other locations were preserved during that, so keep the flags.
621              * This serves to update the emulated overlay, if any. */
622             fbflags = front->flags;
623             surface_modify_location(front, SFLAG_INDRAWABLE, TRUE);
624             front->flags = fbflags;
625         }
626         else
627         {
628             surface_modify_location(front, SFLAG_INDRAWABLE, TRUE);
629             surface_modify_location(back_buffer, SFLAG_INDRAWABLE, TRUE);
630         }
631     }
632     else
633     {
634         surface_modify_location(swapchain->front_buffer, SFLAG_INDRAWABLE, TRUE);
635         /* If the swapeffect is DISCARD, the back buffer is undefined. That means the SYSMEM
636          * and INTEXTURE copies can keep their old content if they have any defined content.
637          * If the swapeffect is COPY, the content remains the same. If it is FLIP however,
638          * the texture / sysmem copy needs to be reloaded from the drawable
639          */
640         if (swapchain->desc.swap_effect == WINED3D_SWAP_EFFECT_FLIP)
641             surface_modify_location(back_buffer, back_buffer->draw_binding, TRUE);
642     }
643
644     if (fb->depth_stencil)
645     {
646         if (swapchain->desc.flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
647                 || fb->depth_stencil->flags & SFLAG_DISCARD)
648         {
649             surface_modify_ds_location(fb->depth_stencil, SFLAG_DISCARDED,
650                     fb->depth_stencil->resource.width,
651                     fb->depth_stencil->resource.height);
652             if (fb->depth_stencil == swapchain->device->onscreen_depth_stencil)
653             {
654                 wined3d_surface_decref(swapchain->device->onscreen_depth_stencil);
655                 swapchain->device->onscreen_depth_stencil = NULL;
656             }
657         }
658     }
659
660     context_release(context);
661 }
662
663 static const struct wined3d_swapchain_ops swapchain_gl_ops =
664 {
665     swapchain_gl_present,
666 };
667
668 /* Helper function that blits the front buffer contents to the target window. */
669 void x11_copy_to_screen(const struct wined3d_swapchain *swapchain, const RECT *rect)
670 {
671     const struct wined3d_surface *front;
672     POINT offset = {0, 0};
673     HDC src_dc, dst_dc;
674     RECT draw_rect;
675     HWND window;
676
677     TRACE("swapchain %p, rect %s.\n", swapchain, wine_dbgstr_rect(rect));
678
679     front = swapchain->front_buffer;
680     if (!(front->resource.usage & WINED3DUSAGE_RENDERTARGET))
681         return;
682
683     if (front->resource.map_count)
684         ERR("Trying to blit a mapped surface.\n");
685
686     TRACE("Copying surface %p to screen.\n", front);
687
688     src_dc = front->hDC;
689     window = swapchain->win_handle;
690     dst_dc = GetDCEx(window, 0, DCX_CLIPSIBLINGS | DCX_CACHE);
691
692     /* Front buffer coordinates are screen coordinates. Map them to the
693      * destination window if not fullscreened. */
694     if (swapchain->desc.windowed)
695         ClientToScreen(window, &offset);
696
697     TRACE("offset %s.\n", wine_dbgstr_point(&offset));
698
699     draw_rect.left = 0;
700     draw_rect.right = front->resource.width;
701     draw_rect.top = 0;
702     draw_rect.bottom = front->resource.height;
703
704     if (rect)
705         IntersectRect(&draw_rect, &draw_rect, rect);
706
707     BitBlt(dst_dc, draw_rect.left - offset.x, draw_rect.top - offset.y,
708             draw_rect.right - draw_rect.left, draw_rect.bottom - draw_rect.top,
709             src_dc, draw_rect.left, draw_rect.top, SRCCOPY);
710     ReleaseDC(window, dst_dc);
711 }
712
713 static void swapchain_gdi_present(struct wined3d_swapchain *swapchain, const RECT *src_rect_in,
714         const RECT *dst_rect_in, const RGNDATA *dirty_region, DWORD flags)
715 {
716     struct wined3d_surface *front, *back;
717
718     front = swapchain->front_buffer;
719     back = swapchain->back_buffers[0];
720
721     /* Flip the DC. */
722     {
723         HDC tmp;
724         tmp = front->hDC;
725         front->hDC = back->hDC;
726         back->hDC = tmp;
727     }
728
729     /* Flip the DIBsection. */
730     {
731         HBITMAP tmp;
732         tmp = front->dib.DIBsection;
733         front->dib.DIBsection = back->dib.DIBsection;
734         back->dib.DIBsection = tmp;
735     }
736
737     /* Flip the surface data. */
738     {
739         void *tmp;
740
741         tmp = front->dib.bitmap_data;
742         front->dib.bitmap_data = back->dib.bitmap_data;
743         back->dib.bitmap_data = tmp;
744
745         tmp = front->resource.allocatedMemory;
746         front->resource.allocatedMemory = back->resource.allocatedMemory;
747         back->resource.allocatedMemory = tmp;
748
749         if (front->resource.heapMemory)
750             ERR("GDI Surface %p has heap memory allocated.\n", front);
751
752         if (back->resource.heapMemory)
753             ERR("GDI Surface %p has heap memory allocated.\n", back);
754     }
755
756     /* FPS support */
757     if (TRACE_ON(fps))
758     {
759         static LONG prev_time, frames;
760         DWORD time = GetTickCount();
761
762         ++frames;
763
764         /* every 1.5 seconds */
765         if (time - prev_time > 1500)
766         {
767             TRACE_(fps)("@ approx %.2ffps\n", 1000.0 * frames / (time - prev_time));
768             prev_time = time;
769             frames = 0;
770         }
771     }
772
773     x11_copy_to_screen(swapchain, NULL);
774 }
775
776 static const struct wined3d_swapchain_ops swapchain_gdi_ops =
777 {
778     swapchain_gdi_present,
779 };
780
781 void swapchain_update_render_to_fbo(struct wined3d_swapchain *swapchain)
782 {
783     RECT client_rect;
784
785     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
786         return;
787
788     if (!swapchain->desc.backbuffer_count)
789     {
790         TRACE("Single buffered rendering.\n");
791         swapchain->render_to_fbo = FALSE;
792         return;
793     }
794
795     GetClientRect(swapchain->win_handle, &client_rect);
796
797     TRACE("Backbuffer %ux%u, window %ux%u.\n",
798             swapchain->desc.backbuffer_width,
799             swapchain->desc.backbuffer_height,
800             client_rect.right, client_rect.bottom);
801     TRACE("Multisample type %#x, quality %#x.\n",
802             swapchain->desc.multisample_type,
803             swapchain->desc.multisample_quality);
804
805     if (!wined3d_settings.always_offscreen && !swapchain->desc.multisample_type
806             && swapchain->desc.backbuffer_width == client_rect.right
807             && swapchain->desc.backbuffer_height == client_rect.bottom)
808     {
809         TRACE("Backbuffer dimensions match window dimensions, rendering onscreen.\n");
810         swapchain->render_to_fbo = FALSE;
811         return;
812     }
813
814     TRACE("Rendering to FBO.\n");
815     swapchain->render_to_fbo = TRUE;
816 }
817
818 /* Do not call while under the GL lock. */
819 static HRESULT swapchain_init(struct wined3d_swapchain *swapchain, enum wined3d_surface_type surface_type,
820         struct wined3d_device *device, struct wined3d_swapchain_desc *desc,
821         void *parent, const struct wined3d_parent_ops *parent_ops)
822 {
823     const struct wined3d_adapter *adapter = device->adapter;
824     const struct wined3d_format *format;
825     struct wined3d_display_mode mode;
826     BOOL displaymode_set = FALSE;
827     RECT client_rect;
828     HWND window;
829     HRESULT hr;
830     UINT i;
831
832     if (desc->backbuffer_count > WINED3DPRESENT_BACK_BUFFER_MAX)
833     {
834         FIXME("The application requested %u back buffers, this is not supported.\n",
835                 desc->backbuffer_count);
836         return WINED3DERR_INVALIDCALL;
837     }
838
839     if (desc->backbuffer_count > 1)
840     {
841         FIXME("The application requested more than one back buffer, this is not properly supported.\n"
842                 "Please configure the application to use double buffering (1 back buffer) if possible.\n");
843     }
844
845     switch (surface_type)
846     {
847         case WINED3D_SURFACE_TYPE_GDI:
848             swapchain->swapchain_ops = &swapchain_gdi_ops;
849             break;
850
851         case WINED3D_SURFACE_TYPE_OPENGL:
852             swapchain->swapchain_ops = &swapchain_gl_ops;
853             break;
854
855         default:
856             ERR("Invalid surface type %#x.\n", surface_type);
857             return WINED3DERR_INVALIDCALL;
858     }
859
860     window = desc->device_window ? desc->device_window : device->create_parms.focus_window;
861
862     swapchain->device = device;
863     swapchain->parent = parent;
864     swapchain->parent_ops = parent_ops;
865     swapchain->ref = 1;
866     swapchain->win_handle = window;
867     swapchain->device_window = window;
868
869     wined3d_get_adapter_display_mode(device->wined3d, adapter->ordinal, &mode, NULL);
870     swapchain->orig_width = mode.width;
871     swapchain->orig_height = mode.height;
872     swapchain->orig_fmt = mode.format_id;
873     format = wined3d_get_format(&adapter->gl_info, mode.format_id);
874
875     GetClientRect(window, &client_rect);
876     if (desc->windowed
877             && (!desc->backbuffer_width || !desc->backbuffer_height
878             || desc->backbuffer_format == WINED3DFMT_UNKNOWN))
879     {
880
881         if (!desc->backbuffer_width)
882         {
883             desc->backbuffer_width = client_rect.right;
884             TRACE("Updating width to %u.\n", desc->backbuffer_width);
885         }
886
887         if (!desc->backbuffer_height)
888         {
889             desc->backbuffer_height = client_rect.bottom;
890             TRACE("Updating height to %u.\n", desc->backbuffer_height);
891         }
892
893         if (desc->backbuffer_format == WINED3DFMT_UNKNOWN)
894         {
895             desc->backbuffer_format = swapchain->orig_fmt;
896             TRACE("Updating format to %s.\n", debug_d3dformat(swapchain->orig_fmt));
897         }
898     }
899     swapchain->desc = *desc;
900     swapchain_update_render_to_fbo(swapchain);
901
902     TRACE("Creating front buffer.\n");
903     if (FAILED(hr = device->device_parent->ops->create_swapchain_surface(device->device_parent, parent,
904             swapchain->desc.backbuffer_width, swapchain->desc.backbuffer_height,
905             swapchain->desc.backbuffer_format, WINED3DUSAGE_RENDERTARGET,
906             swapchain->desc.multisample_type, swapchain->desc.multisample_quality,
907             &swapchain->front_buffer)))
908     {
909         WARN("Failed to create front buffer, hr %#x.\n", hr);
910         goto err;
911     }
912
913     if (swapchain->front_buffer->container.type == WINED3D_CONTAINER_NONE)
914         surface_set_container(swapchain->front_buffer, WINED3D_CONTAINER_SWAPCHAIN, swapchain);
915     if (surface_type == WINED3D_SURFACE_TYPE_OPENGL)
916         surface_modify_location(swapchain->front_buffer, SFLAG_INDRAWABLE, TRUE);
917
918     /* MSDN says we're only allowed a single fullscreen swapchain per device,
919      * so we should really check to see if there is a fullscreen swapchain
920      * already. Does a single head count as full screen? */
921
922     if (!desc->windowed)
923     {
924         struct wined3d_display_mode mode;
925
926         /* Change the display settings */
927         mode.width = desc->backbuffer_width;
928         mode.height = desc->backbuffer_height;
929         mode.format_id = desc->backbuffer_format;
930         mode.refresh_rate = desc->refresh_rate;
931         mode.scanline_ordering = WINED3D_SCANLINE_ORDERING_UNKNOWN;
932
933         if (FAILED(hr = wined3d_set_adapter_display_mode(device->wined3d, device->adapter->ordinal, &mode)))
934         {
935             WARN("Failed to set display mode, hr %#x.\n", hr);
936             goto err;
937         }
938         displaymode_set = TRUE;
939     }
940
941     if (surface_type == WINED3D_SURFACE_TYPE_OPENGL)
942     {
943         static const enum wined3d_format_id formats[] =
944         {
945             WINED3DFMT_D24_UNORM_S8_UINT,
946             WINED3DFMT_D32_UNORM,
947             WINED3DFMT_R24_UNORM_X8_TYPELESS,
948             WINED3DFMT_D16_UNORM,
949             WINED3DFMT_S1_UINT_D15_UNORM
950         };
951
952         const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
953
954         swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(*swapchain->context));
955         if (!swapchain->context)
956         {
957             ERR("Failed to create the context array.\n");
958             hr = E_OUTOFMEMORY;
959             goto err;
960         }
961         swapchain->num_contexts = 1;
962
963         /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
964          * You are able to add a depth + stencil surface at a later stage when you need it.
965          * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
966          * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
967          * context, need torecreate shaders, textures and other resources.
968          *
969          * The context manager already takes care of the state problem and for the other tasks code from Reset
970          * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
971          * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
972          * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
973          * issue needs to be fixed. */
974         for (i = 0; i < (sizeof(formats) / sizeof(*formats)); i++)
975         {
976             swapchain->ds_format = wined3d_get_format(gl_info, formats[i]);
977             swapchain->context[0] = context_create(swapchain, swapchain->front_buffer, swapchain->ds_format);
978             if (swapchain->context[0]) break;
979             TRACE("Depth stencil format %s is not supported, trying next format\n",
980                   debug_d3dformat(formats[i]));
981         }
982
983         if (!swapchain->context[0])
984         {
985             WARN("Failed to create context.\n");
986             hr = WINED3DERR_NOTAVAILABLE;
987             goto err;
988         }
989
990         if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
991                 && (!desc->enable_auto_depth_stencil
992                 || swapchain->desc.auto_depth_stencil_format != swapchain->ds_format->id))
993         {
994             FIXME("Add OpenGL context recreation support to context_validate_onscreen_formats\n");
995         }
996         context_release(swapchain->context[0]);
997     }
998
999     if (swapchain->desc.backbuffer_count > 0)
1000     {
1001         swapchain->back_buffers = HeapAlloc(GetProcessHeap(), 0,
1002                 sizeof(*swapchain->back_buffers) * swapchain->desc.backbuffer_count);
1003         if (!swapchain->back_buffers)
1004         {
1005             ERR("Failed to allocate backbuffer array memory.\n");
1006             hr = E_OUTOFMEMORY;
1007             goto err;
1008         }
1009
1010         for (i = 0; i < swapchain->desc.backbuffer_count; ++i)
1011         {
1012             TRACE("Creating back buffer %u.\n", i);
1013             if (FAILED(hr = device->device_parent->ops->create_swapchain_surface(device->device_parent, parent,
1014                     swapchain->desc.backbuffer_width, swapchain->desc.backbuffer_height,
1015                     swapchain->desc.backbuffer_format, WINED3DUSAGE_RENDERTARGET,
1016                     swapchain->desc.multisample_type, swapchain->desc.multisample_quality,
1017                     &swapchain->back_buffers[i])))
1018             {
1019                 WARN("Failed to create back buffer %u, hr %#x.\n", i, hr);
1020                 goto err;
1021             }
1022             if (swapchain->back_buffers[i]->container.type == WINED3D_CONTAINER_NONE)
1023                 surface_set_container(swapchain->back_buffers[i], WINED3D_CONTAINER_SWAPCHAIN, swapchain);
1024         }
1025     }
1026
1027     /* Swapchains share the depth/stencil buffer, so only create a single depthstencil surface. */
1028     if (desc->enable_auto_depth_stencil && surface_type == WINED3D_SURFACE_TYPE_OPENGL)
1029     {
1030         TRACE("Creating depth/stencil buffer.\n");
1031         if (!device->auto_depth_stencil)
1032         {
1033             if (FAILED(hr = device->device_parent->ops->create_swapchain_surface(device->device_parent,
1034                     device->device_parent, swapchain->desc.backbuffer_width, swapchain->desc.backbuffer_height,
1035                     swapchain->desc.auto_depth_stencil_format, WINED3DUSAGE_DEPTHSTENCIL,
1036                     swapchain->desc.multisample_type, swapchain->desc.multisample_quality,
1037                     &device->auto_depth_stencil)))
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->desc.backbuffer_count; ++i)
1071         {
1072             if (swapchain->back_buffers[i])
1073             {
1074                 surface_set_container(swapchain->back_buffers[i], WINED3D_CONTAINER_NONE, NULL);
1075                 wined3d_surface_decref(swapchain->back_buffers[i]);
1076             }
1077         }
1078         HeapFree(GetProcessHeap(), 0, swapchain->back_buffers);
1079     }
1080
1081     if (swapchain->context)
1082     {
1083         if (swapchain->context[0])
1084         {
1085             context_release(swapchain->context[0]);
1086             context_destroy(device, swapchain->context[0]);
1087             swapchain->num_contexts = 0;
1088         }
1089         HeapFree(GetProcessHeap(), 0, swapchain->context);
1090     }
1091
1092     if (swapchain->front_buffer)
1093     {
1094         surface_set_container(swapchain->front_buffer, WINED3D_CONTAINER_NONE, NULL);
1095         wined3d_surface_decref(swapchain->front_buffer);
1096     }
1097
1098     return hr;
1099 }
1100
1101 /* Do not call while under the GL lock. */
1102 HRESULT CDECL wined3d_swapchain_create(struct wined3d_device *device,
1103         struct wined3d_swapchain_desc *desc, enum wined3d_surface_type surface_type,
1104         void *parent, const struct wined3d_parent_ops *parent_ops,
1105         struct wined3d_swapchain **swapchain)
1106 {
1107     struct wined3d_swapchain *object;
1108     HRESULT hr;
1109
1110     TRACE("device %p, desc %p, swapchain %p, parent %p, surface_type %#x.\n",
1111             device, desc, swapchain, parent, surface_type);
1112
1113     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1114     if (!object)
1115     {
1116         ERR("Failed to allocate swapchain memory.\n");
1117         return E_OUTOFMEMORY;
1118     }
1119
1120     hr = swapchain_init(object, surface_type, device, desc, parent, parent_ops);
1121     if (FAILED(hr))
1122     {
1123         WARN("Failed to initialize swapchain, hr %#x.\n", hr);
1124         HeapFree(GetProcessHeap(), 0, object);
1125         return hr;
1126     }
1127
1128     TRACE("Created swapchain %p.\n", object);
1129     *swapchain = object;
1130
1131     return WINED3D_OK;
1132 }
1133
1134 /* Do not call while under the GL lock. */
1135 static struct wined3d_context *swapchain_create_context(struct wined3d_swapchain *swapchain)
1136 {
1137     struct wined3d_context **newArray;
1138     struct wined3d_context *ctx;
1139
1140     TRACE("Creating a new context for swapchain %p, thread %u.\n", swapchain, GetCurrentThreadId());
1141
1142     if (!(ctx = context_create(swapchain, swapchain->front_buffer, swapchain->ds_format)))
1143     {
1144         ERR("Failed to create a new context for the swapchain\n");
1145         return NULL;
1146     }
1147     context_release(ctx);
1148
1149     newArray = HeapAlloc(GetProcessHeap(), 0, sizeof(*newArray) * (swapchain->num_contexts + 1));
1150     if(!newArray) {
1151         ERR("Out of memory when trying to allocate a new context array\n");
1152         context_destroy(swapchain->device, ctx);
1153         return NULL;
1154     }
1155     memcpy(newArray, swapchain->context, sizeof(*newArray) * swapchain->num_contexts);
1156     HeapFree(GetProcessHeap(), 0, swapchain->context);
1157     newArray[swapchain->num_contexts] = ctx;
1158     swapchain->context = newArray;
1159     swapchain->num_contexts++;
1160
1161     TRACE("Returning context %p\n", ctx);
1162     return ctx;
1163 }
1164
1165 void swapchain_destroy_contexts(struct wined3d_swapchain *swapchain)
1166 {
1167     unsigned int i;
1168
1169     for (i = 0; i < swapchain->num_contexts; ++i)
1170     {
1171         context_destroy(swapchain->device, swapchain->context[i]);
1172     }
1173     swapchain->num_contexts = 0;
1174 }
1175
1176 struct wined3d_context *swapchain_get_context(struct wined3d_swapchain *swapchain)
1177 {
1178     DWORD tid = GetCurrentThreadId();
1179     unsigned int i;
1180
1181     for (i = 0; i < swapchain->num_contexts; ++i)
1182     {
1183         if (swapchain->context[i]->tid == tid)
1184             return swapchain->context[i];
1185     }
1186
1187     /* Create a new context for the thread */
1188     return swapchain_create_context(swapchain);
1189 }
1190
1191 void get_drawable_size_swapchain(const struct wined3d_context *context, UINT *width, UINT *height)
1192 {
1193     /* The drawable size of an onscreen drawable is the surface size.
1194      * (Actually: The window size, but the surface is created in window size) */
1195     *width = context->current_rt->resource.width;
1196     *height = context->current_rt->resource.height;
1197 }
1198
1199 HDC swapchain_get_backup_dc(struct wined3d_swapchain *swapchain)
1200 {
1201     if (!swapchain->backup_dc)
1202     {
1203         TRACE("Creating the backup window for swapchain %p.\n", swapchain);
1204
1205         if (!(swapchain->backup_wnd = CreateWindowA(WINED3D_OPENGL_WINDOW_CLASS_NAME, "WineD3D fake window",
1206                 WS_OVERLAPPEDWINDOW, 10, 10, 10, 10, NULL, NULL, NULL, NULL)))
1207         {
1208             ERR("Failed to create a window.\n");
1209             return NULL;
1210         }
1211
1212         if (!(swapchain->backup_dc = GetDC(swapchain->backup_wnd)))
1213         {
1214             ERR("Failed to get a DC.\n");
1215             DestroyWindow(swapchain->backup_wnd);
1216             swapchain->backup_wnd = NULL;
1217             return NULL;
1218         }
1219     }
1220
1221     return swapchain->backup_dc;
1222 }
1223
1224 void swapchain_update_draw_bindings(struct wined3d_swapchain *swapchain)
1225 {
1226     UINT i;
1227
1228     surface_update_draw_binding(swapchain->front_buffer);
1229
1230     for (i = 0; i < swapchain->desc.backbuffer_count; ++i)
1231     {
1232         surface_update_draw_binding(swapchain->back_buffers[i]);
1233     }
1234 }