quartz: Make sure video window is actually destroyed.
[wine] / dlls / wined3d / swapchain.c
1 /*
2  *IDirect3DSwapChain9 implementation
3  *
4  *Copyright 2002-2003 Jason Edmeades
5  *Copyright 2002-2003 Raphael Junqueira
6  *Copyright 2005 Oliver Stieber
7  *Copyright 2007-2008 Stefan Dösinger for CodeWeavers
8  *
9  *This library is free software; you can redistribute it and/or
10  *modify it under the terms of the GNU Lesser General Public
11  *License as published by the Free Software Foundation; either
12  *version 2.1 of the License, or (at your option) any later version.
13  *
14  *This library is distributed in the hope that it will be useful,
15  *but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  *Lesser General Public License for more details.
18  *
19  *You should have received a copy of the GNU Lesser General Public
20  *License along with this library; if not, write to the Free Software
21  *Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include "config.h"
25 #include "wined3d_private.h"
26
27
28 /*TODO: some of the additional parameters may be required to
29     set the gamma ramp (for some weird reason microsoft have left swap gammaramp in device
30     but it operates on a swapchain, it may be a good idea to move it to IWineD3DSwapChain for IWineD3D)*/
31
32
33 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
34 WINE_DECLARE_DEBUG_CHANNEL(fps);
35
36 /* Do not call while under the GL lock. */
37 static void WINAPI IWineD3DSwapChainImpl_Destroy(IWineD3DSwapChain *iface)
38 {
39     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
40     WINED3DDISPLAYMODE mode;
41     unsigned int i;
42
43     TRACE("Destroying swapchain %p\n", iface);
44
45     IWineD3DSwapChain_SetGammaRamp(iface, 0, &This->orig_gamma);
46
47     /* Release the swapchain's draw buffers. Make sure This->back_buffers[0] is
48      * the last buffer to be destroyed, FindContext() depends on that. */
49     if (This->front_buffer)
50     {
51         surface_set_container(This->front_buffer, WINED3D_CONTAINER_NONE, NULL);
52         if (IWineD3DSurface_Release((IWineD3DSurface *)This->front_buffer))
53         {
54             WARN("(%p) Something's still holding the front buffer (%p).\n",
55                     This, This->front_buffer);
56         }
57         This->front_buffer = NULL;
58     }
59
60     if (This->back_buffers)
61     {
62         UINT i = This->presentParms.BackBufferCount;
63
64         while (i--)
65         {
66             surface_set_container(This->back_buffers[i], WINED3D_CONTAINER_NONE, NULL);
67             if (IWineD3DSurface_Release((IWineD3DSurface *)This->back_buffers[i]))
68                 WARN("(%p) Something's still holding back buffer %u (%p).\n",
69                         This, i, This->back_buffers[i]);
70         }
71         HeapFree(GetProcessHeap(), 0, This->back_buffers);
72         This->back_buffers = NULL;
73     }
74
75     for (i = 0; i < This->num_contexts; ++i)
76     {
77         context_destroy(This->device, This->context[i]);
78     }
79     /* Restore the screen resolution if we rendered in fullscreen
80      * This will restore the screen resolution to what it was before creating the swapchain. In case of d3d8 and d3d9
81      * this will be the original desktop resolution. In case of d3d7 this will be a NOP because ddraw sets the resolution
82      * before starting up Direct3D, thus orig_width and orig_height will be equal to the modes in the presentation params
83      */
84     if (!This->presentParms.Windowed && This->presentParms.AutoRestoreDisplayMode)
85     {
86         mode.Width = This->orig_width;
87         mode.Height = This->orig_height;
88         mode.RefreshRate = 0;
89         mode.Format = This->orig_fmt;
90         IWineD3DDevice_SetDisplayMode((IWineD3DDevice *)This->device, 0, &mode);
91     }
92
93     HeapFree(GetProcessHeap(), 0, This->context);
94     HeapFree(GetProcessHeap(), 0, This);
95 }
96
97 /* A GL context is provided by the caller */
98 static void swapchain_blit(IWineD3DSwapChainImpl *This, struct wined3d_context *context,
99         const RECT *src_rect, const RECT *dst_rect)
100 {
101     IWineD3DDeviceImpl *device = This->device;
102     IWineD3DSurfaceImpl *backbuffer = This->back_buffers[0];
103     UINT src_w = src_rect->right - src_rect->left;
104     UINT src_h = src_rect->bottom - src_rect->top;
105     GLenum gl_filter;
106     const struct wined3d_gl_info *gl_info = context->gl_info;
107     RECT win_rect;
108     UINT win_h;
109
110     TRACE("swapchain %p, context %p, src_rect %s, dst_rect %s.\n",
111             This, context, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect));
112
113     if (src_w == dst_rect->right - dst_rect->left && src_h == dst_rect->bottom - dst_rect->top)
114         gl_filter = GL_NEAREST;
115     else
116         gl_filter = GL_LINEAR;
117
118     GetClientRect(This->win_handle, &win_rect);
119     win_h = win_rect.bottom - win_rect.top;
120
121     if (gl_info->fbo_ops.glBlitFramebuffer && is_identity_fixup(backbuffer->resource.format->color_fixup))
122     {
123         ENTER_GL();
124         context_apply_fbo_state_blit(context, GL_READ_FRAMEBUFFER, backbuffer, NULL, SFLAG_INTEXTURE);
125         glReadBuffer(GL_COLOR_ATTACHMENT0);
126
127         context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, NULL);
128         context_set_draw_buffer(context, GL_BACK);
129
130         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
131         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
132         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
133         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
134         IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
135
136         glDisable(GL_SCISSOR_TEST);
137         IWineD3DDeviceImpl_MarkStateDirty(This->device, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
138
139         /* Note that the texture is upside down */
140         gl_info->fbo_ops.glBlitFramebuffer(src_rect->left, src_rect->top, src_rect->right, src_rect->bottom,
141                 dst_rect->left, win_h - dst_rect->top, dst_rect->right, win_h - dst_rect->bottom,
142                 GL_COLOR_BUFFER_BIT, gl_filter);
143         checkGLcall("Swapchain present blit(EXT_framebuffer_blit)\n");
144         LEAVE_GL();
145     }
146     else
147     {
148         struct wined3d_context *context2;
149         float tex_left = src_rect->left;
150         float tex_top = src_rect->top;
151         float tex_right = src_rect->right;
152         float tex_bottom = src_rect->bottom;
153
154         context2 = context_acquire(This->device, This->back_buffers[0]);
155         context_apply_blit_state(context2, device);
156
157         if (backbuffer->flags & SFLAG_NORMCOORD)
158         {
159             tex_left /= src_w;
160             tex_right /= src_w;
161             tex_top /= src_h;
162             tex_bottom /= src_h;
163         }
164
165         if (is_complex_fixup(backbuffer->resource.format->color_fixup))
166             gl_filter = GL_NEAREST;
167
168         ENTER_GL();
169         context_bind_fbo(context2, GL_FRAMEBUFFER, NULL);
170
171         /* Set up the texture. The surface is not in a IWineD3D*Texture container,
172          * so there are no d3d texture settings to dirtify
173          */
174         device->blitter->set_shader((IWineD3DDevice *) device, backbuffer);
175         glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MIN_FILTER, gl_filter);
176         glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MAG_FILTER, gl_filter);
177
178         context_set_draw_buffer(context, GL_BACK);
179
180         /* Set the viewport to the destination rectandle, disable any projection
181          * transformation set up by context_apply_blit_state(), and draw a
182          * (-1,-1)-(1,1) quad.
183          *
184          * Back up viewport and matrix to avoid breaking last_was_blit
185          *
186          * Note that context_apply_blit_state() set up viewport and ortho to
187          * match the surface size - we want the GL drawable(=window) size. */
188         glPushAttrib(GL_VIEWPORT_BIT);
189         glViewport(dst_rect->left, win_h - dst_rect->bottom, dst_rect->right, win_h - dst_rect->top);
190         glMatrixMode(GL_PROJECTION);
191         glPushMatrix();
192         glLoadIdentity();
193
194         glBegin(GL_QUADS);
195             /* bottom left */
196             glTexCoord2f(tex_left, tex_bottom);
197             glVertex2i(-1, -1);
198
199             /* top left */
200             glTexCoord2f(tex_left, tex_top);
201             glVertex2i(-1, 1);
202
203             /* top right */
204             glTexCoord2f(tex_right, tex_top);
205             glVertex2i(1, 1);
206
207             /* bottom right */
208             glTexCoord2f(tex_right, tex_bottom);
209             glVertex2i(1, -1);
210         glEnd();
211
212         glPopMatrix();
213         glPopAttrib();
214
215         device->blitter->unset_shader((IWineD3DDevice *) device);
216         checkGLcall("Swapchain present blit(manual)\n");
217         LEAVE_GL();
218
219         context_release(context2);
220     }
221 }
222
223 static HRESULT WINAPI IWineD3DSwapChainImpl_Present(IWineD3DSwapChain *iface,
224         const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride,
225         const RGNDATA *pDirtyRegion, DWORD flags)
226 {
227     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
228     const struct wined3d_gl_info *gl_info;
229     struct wined3d_context *context;
230     RECT src_rect, dst_rect;
231     BOOL render_to_fbo;
232     unsigned int sync;
233     int retval;
234
235     IWineD3DSwapChain_SetDestWindowOverride(iface, hDestWindowOverride);
236
237     context = context_acquire(This->device, This->back_buffers[0]);
238     if (!context->valid)
239     {
240         context_release(context);
241         WARN("Invalid context, skipping present.\n");
242         return WINED3D_OK;
243     }
244
245     gl_info = context->gl_info;
246
247     /* Render the cursor onto the back buffer, using our nifty directdraw blitting code :-) */
248     if (This->device->bCursorVisible && This->device->cursorTexture)
249     {
250         IWineD3DSurfaceImpl cursor;
251         RECT destRect =
252         {
253             This->device->xScreenSpace - This->device->xHotSpot,
254             This->device->yScreenSpace - This->device->yHotSpot,
255             This->device->xScreenSpace + This->device->cursorWidth - This->device->xHotSpot,
256             This->device->yScreenSpace + This->device->cursorHeight - This->device->yHotSpot,
257         };
258         TRACE("Rendering the cursor. Creating fake surface at %p\n", &cursor);
259         /* Build a fake surface to call the Blitting code. It is not possible to use the interface passed by
260          * the application because we are only supposed to copy the information out. Using a fake surface
261          * allows to use the Blitting engine and avoid copying the whole texture -> render target blitting code.
262          */
263         memset(&cursor, 0, sizeof(cursor));
264         cursor.lpVtbl = &IWineD3DSurface_Vtbl;
265         cursor.resource.ref = 1;
266         cursor.resource.device = This->device;
267         cursor.resource.pool = WINED3DPOOL_SCRATCH;
268         cursor.resource.format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
269         cursor.resource.resourceType = WINED3DRTYPE_SURFACE;
270         cursor.texture_name = This->device->cursorTexture;
271         cursor.texture_target = GL_TEXTURE_2D;
272         cursor.texture_level = 0;
273         cursor.currentDesc.Width = This->device->cursorWidth;
274         cursor.currentDesc.Height = This->device->cursorHeight;
275         /* The cursor must have pow2 sizes */
276         cursor.pow2Width = cursor.currentDesc.Width;
277         cursor.pow2Height = cursor.currentDesc.Height;
278         /* The surface is in the texture */
279         cursor.flags |= SFLAG_INTEXTURE;
280         /* DDBLT_KEYSRC will cause BltOverride to enable the alpha test with GL_NOTEQUAL, 0.0,
281          * which is exactly what we want :-)
282          */
283         if (This->presentParms.Windowed) {
284             MapWindowPoints(NULL, This->win_handle, (LPPOINT)&destRect, 2);
285         }
286         IWineD3DSurface_Blt((IWineD3DSurface *)This->back_buffers[0], &destRect, (IWineD3DSurface *)&cursor,
287                 NULL, WINEDDBLT_KEYSRC, NULL, WINED3DTEXF_POINT);
288     }
289
290     if (This->device->logo_surface)
291     {
292         /* Blit the logo into the upper left corner of the drawable. */
293         IWineD3DSurface_BltFast((IWineD3DSurface *)This->back_buffers[0], 0, 0,
294                 This->device->logo_surface, NULL, WINEDDBLTFAST_SRCCOLORKEY);
295     }
296
297     TRACE("Presenting HDC %p.\n", context->hdc);
298
299     render_to_fbo = This->render_to_fbo;
300
301     if (pSourceRect)
302     {
303         src_rect = *pSourceRect;
304         if (!render_to_fbo && (src_rect.left || src_rect.top
305                 || src_rect.right != This->presentParms.BackBufferWidth
306                 || src_rect.bottom != This->presentParms.BackBufferHeight))
307         {
308             render_to_fbo = TRUE;
309         }
310     }
311     else
312     {
313         src_rect.left = 0;
314         src_rect.top = 0;
315         src_rect.right = This->presentParms.BackBufferWidth;
316         src_rect.bottom = This->presentParms.BackBufferHeight;
317     }
318
319     if (pDestRect) dst_rect = *pDestRect;
320     else GetClientRect(This->win_handle, &dst_rect);
321
322     if (!render_to_fbo && (dst_rect.left || dst_rect.top
323             || dst_rect.right != This->presentParms.BackBufferWidth
324             || dst_rect.bottom != This->presentParms.BackBufferHeight))
325     {
326         render_to_fbo = TRUE;
327     }
328
329     /* Rendering to a window of different size, presenting partial rectangles,
330      * or rendering to a different window needs help from FBO_blit or a textured
331      * draw. Render the swapchain to a FBO in the future.
332      *
333      * Note that FBO_blit from the backbuffer to the frontbuffer cannot solve
334      * all these issues - this fails if the window is smaller than the backbuffer.
335      */
336     if (!This->render_to_fbo && render_to_fbo && wined3d_settings.offscreen_rendering_mode == ORM_FBO)
337     {
338         surface_load_location(This->back_buffers[0], SFLAG_INTEXTURE, NULL);
339         surface_modify_location(This->back_buffers[0], SFLAG_INDRAWABLE, FALSE);
340         This->render_to_fbo = TRUE;
341     }
342
343     if(This->render_to_fbo)
344     {
345         /* This codepath should only be hit with the COPY swapeffect. Otherwise a backbuffer-
346          * window size mismatch is impossible(fullscreen) and src and dst rectangles are
347          * not allowed(they need the COPY swapeffect)
348          *
349          * The DISCARD swap effect is ok as well since any backbuffer content is allowed after
350          * the swap
351          */
352         if(This->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP )
353         {
354             FIXME("Render-to-fbo with WINED3DSWAPEFFECT_FLIP\n");
355         }
356
357         swapchain_blit(This, context, &src_rect, &dst_rect);
358     }
359
360     if (This->num_contexts > 1) wglFinish();
361     SwapBuffers(context->hdc); /* TODO: cycle through the swapchain buffers */
362
363     TRACE("SwapBuffers called, Starting new frame\n");
364     /* FPS support */
365     if (TRACE_ON(fps))
366     {
367         DWORD time = GetTickCount();
368         This->frames++;
369         /* every 1.5 seconds */
370         if (time - This->prev_time > 1500) {
371             TRACE_(fps)("%p @ approx %.2ffps\n", This, 1000.0*This->frames/(time - This->prev_time));
372             This->prev_time = time;
373             This->frames = 0;
374         }
375     }
376
377     /* This is disabled, but the code left in for debug purposes.
378      *
379      * Since we're allowed to modify the new back buffer on a D3DSWAPEFFECT_DISCARD flip,
380      * we can clear it with some ugly color to make bad drawing visible and ease debugging.
381      * The Debug runtime does the same on Windows. However, a few games do not redraw the
382      * screen properly, like Max Payne 2, which leaves a few pixels undefined.
383      *
384      * Tests show that the content of the back buffer after a discard flip is indeed not
385      * reliable, so no game can depend on the exact content. However, it resembles the
386      * old contents in some way, for example by showing fragments at other locations. In
387      * general, the color theme is still intact. So Max payne, which draws rather dark scenes
388      * gets a dark background image. If we clear it with a bright ugly color, the game's
389      * bug shows up much more than it does on Windows, and the players see single pixels
390      * with wrong colors.
391      * (The Max Payne bug has been confirmed on Windows with the debug runtime)
392      */
393     if (FALSE && This->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD) {
394         TRACE("Clearing the color buffer with cyan color\n");
395
396         IWineD3DDevice_Clear((IWineD3DDevice *)This->device, 0, NULL,
397                 WINED3DCLEAR_TARGET, 0xff00ffff, 1.0f, 0);
398     }
399
400     if (!This->render_to_fbo && ((This->front_buffer->flags & SFLAG_INSYSMEM)
401             || (This->back_buffers[0]->flags & SFLAG_INSYSMEM)))
402     {
403         /* Both memory copies of the surfaces are ok, flip them around too instead of dirtifying
404          * Doesn't work with render_to_fbo because we're not flipping
405          */
406         IWineD3DSurfaceImpl *front = This->front_buffer;
407         IWineD3DSurfaceImpl *back = This->back_buffers[0];
408
409         if(front->resource.size == back->resource.size) {
410             DWORD fbflags;
411             flip_surface(front, back);
412
413             /* Tell the front buffer surface that is has been modified. However,
414              * the other locations were preserved during that, so keep the flags.
415              * This serves to update the emulated overlay, if any. */
416             fbflags = front->flags;
417             surface_modify_location(front, SFLAG_INDRAWABLE, TRUE);
418             front->flags = fbflags;
419         }
420         else
421         {
422             surface_modify_location(front, SFLAG_INDRAWABLE, TRUE);
423             surface_modify_location(back, SFLAG_INDRAWABLE, TRUE);
424         }
425     }
426     else
427     {
428         surface_modify_location(This->front_buffer, SFLAG_INDRAWABLE, TRUE);
429         /* If the swapeffect is DISCARD, the back buffer is undefined. That means the SYSMEM
430          * and INTEXTURE copies can keep their old content if they have any defined content.
431          * If the swapeffect is COPY, the content remains the same. If it is FLIP however,
432          * the texture / sysmem copy needs to be reloaded from the drawable
433          */
434         if (This->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP)
435         {
436             surface_modify_location(This->back_buffers[0], SFLAG_INDRAWABLE, TRUE);
437         }
438     }
439
440     if (This->device->depth_stencil)
441     {
442         if (This->presentParms.Flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
443                 || This->device->depth_stencil->flags & SFLAG_DISCARD)
444         {
445             surface_modify_ds_location(This->device->depth_stencil, SFLAG_DS_DISCARDED,
446                     This->device->depth_stencil->currentDesc.Width,
447                     This->device->depth_stencil->currentDesc.Height);
448             if (This->device->depth_stencil == This->device->onscreen_depth_stencil)
449             {
450                 IWineD3DSurface_Release((IWineD3DSurface *)This->device->onscreen_depth_stencil);
451                 This->device->onscreen_depth_stencil = NULL;
452             }
453         }
454     }
455
456     if (This->presentParms.PresentationInterval != WINED3DPRESENT_INTERVAL_IMMEDIATE
457             && gl_info->supported[SGI_VIDEO_SYNC])
458     {
459         if ((retval = GL_EXTCALL(glXGetVideoSyncSGI(&sync))))
460             ERR("glXGetVideoSyncSGI failed(retval = %d\n", retval);
461
462         switch(This->presentParms.PresentationInterval) {
463             case WINED3DPRESENT_INTERVAL_DEFAULT:
464             case WINED3DPRESENT_INTERVAL_ONE:
465                 if(sync <= This->vSyncCounter) {
466                     retval = GL_EXTCALL(glXWaitVideoSyncSGI(1, 0, &This->vSyncCounter));
467                 } else {
468                     This->vSyncCounter = sync;
469                 }
470                 break;
471             case WINED3DPRESENT_INTERVAL_TWO:
472                 if(sync <= This->vSyncCounter + 1) {
473                     retval = GL_EXTCALL(glXWaitVideoSyncSGI(2, This->vSyncCounter & 0x1, &This->vSyncCounter));
474                 } else {
475                     This->vSyncCounter = sync;
476                 }
477                 break;
478             case WINED3DPRESENT_INTERVAL_THREE:
479                 if(sync <= This->vSyncCounter + 2) {
480                     retval = GL_EXTCALL(glXWaitVideoSyncSGI(3, This->vSyncCounter % 0x3, &This->vSyncCounter));
481                 } else {
482                     This->vSyncCounter = sync;
483                 }
484                 break;
485             case WINED3DPRESENT_INTERVAL_FOUR:
486                 if(sync <= This->vSyncCounter + 3) {
487                     retval = GL_EXTCALL(glXWaitVideoSyncSGI(4, This->vSyncCounter & 0x3, &This->vSyncCounter));
488                 } else {
489                     This->vSyncCounter = sync;
490                 }
491                 break;
492             default:
493                 FIXME("Unknown presentation interval %08x\n", This->presentParms.PresentationInterval);
494         }
495     }
496
497     context_release(context);
498
499     TRACE("returning\n");
500     return WINED3D_OK;
501 }
502
503 static HRESULT WINAPI IWineD3DSwapChainImpl_SetDestWindowOverride(IWineD3DSwapChain *iface, HWND window)
504 {
505     IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)iface;
506
507     if (!window) window = swapchain->device_window;
508     if (window == swapchain->win_handle) return WINED3D_OK;
509
510     TRACE("Setting swapchain %p window from %p to %p\n", swapchain, swapchain->win_handle, window);
511     swapchain->win_handle = window;
512
513     return WINED3D_OK;
514 }
515
516 static const IWineD3DSwapChainVtbl IWineD3DSwapChain_Vtbl =
517 {
518     /* IUnknown */
519     IWineD3DBaseSwapChainImpl_QueryInterface,
520     IWineD3DBaseSwapChainImpl_AddRef,
521     IWineD3DBaseSwapChainImpl_Release,
522     /* IWineD3DSwapChain */
523     IWineD3DBaseSwapChainImpl_GetParent,
524     IWineD3DSwapChainImpl_Destroy,
525     IWineD3DBaseSwapChainImpl_GetDevice,
526     IWineD3DSwapChainImpl_Present,
527     IWineD3DSwapChainImpl_SetDestWindowOverride,
528     IWineD3DBaseSwapChainImpl_GetFrontBufferData,
529     IWineD3DBaseSwapChainImpl_GetBackBuffer,
530     IWineD3DBaseSwapChainImpl_GetRasterStatus,
531     IWineD3DBaseSwapChainImpl_GetDisplayMode,
532     IWineD3DBaseSwapChainImpl_GetPresentParameters,
533     IWineD3DBaseSwapChainImpl_SetGammaRamp,
534     IWineD3DBaseSwapChainImpl_GetGammaRamp
535 };
536
537 /* Do not call while under the GL lock. */
538 HRESULT swapchain_init(IWineD3DSwapChainImpl *swapchain, WINED3DSURFTYPE surface_type,
539         IWineD3DDeviceImpl *device, WINED3DPRESENT_PARAMETERS *present_parameters, void *parent)
540 {
541     const struct wined3d_adapter *adapter = device->adapter;
542     const struct wined3d_format *format;
543     BOOL displaymode_set = FALSE;
544     WINED3DDISPLAYMODE mode;
545     RECT client_rect;
546     HWND window;
547     HRESULT hr;
548     UINT i;
549
550     if (present_parameters->BackBufferCount > WINED3DPRESENT_BACK_BUFFER_MAX)
551     {
552         FIXME("The application requested %u back buffers, this is not supported.\n",
553                 present_parameters->BackBufferCount);
554         return WINED3DERR_INVALIDCALL;
555     }
556
557     if (present_parameters->BackBufferCount > 1)
558     {
559         FIXME("The application requested more than one back buffer, this is not properly supported.\n"
560                 "Please configure the application to use double buffering (1 back buffer) if possible.\n");
561     }
562
563     switch (surface_type)
564     {
565         case SURFACE_GDI:
566             swapchain->lpVtbl = &IWineGDISwapChain_Vtbl;
567             break;
568
569         case SURFACE_OPENGL:
570             swapchain->lpVtbl = &IWineD3DSwapChain_Vtbl;
571             break;
572
573         case SURFACE_UNKNOWN:
574             FIXME("Caller tried to create a SURFACE_UNKNOWN swapchain.\n");
575             return WINED3DERR_INVALIDCALL;
576     }
577
578     window = present_parameters->hDeviceWindow ? present_parameters->hDeviceWindow : device->createParms.hFocusWindow;
579
580     swapchain->device = device;
581     swapchain->parent = parent;
582     swapchain->ref = 1;
583     swapchain->win_handle = window;
584     swapchain->device_window = window;
585
586     IWineD3D_GetAdapterDisplayMode(device->wined3d, adapter->ordinal, &mode);
587     swapchain->orig_width = mode.Width;
588     swapchain->orig_height = mode.Height;
589     swapchain->orig_fmt = mode.Format;
590     format = wined3d_get_format(&adapter->gl_info, mode.Format);
591
592     GetClientRect(window, &client_rect);
593     if (present_parameters->Windowed
594             && (!present_parameters->BackBufferWidth || !present_parameters->BackBufferHeight
595             || present_parameters->BackBufferFormat == WINED3DFMT_UNKNOWN))
596     {
597
598         if (!present_parameters->BackBufferWidth)
599         {
600             present_parameters->BackBufferWidth = client_rect.right;
601             TRACE("Updating width to %u.\n", present_parameters->BackBufferWidth);
602         }
603
604         if (!present_parameters->BackBufferHeight)
605         {
606             present_parameters->BackBufferHeight = client_rect.bottom;
607             TRACE("Updating height to %u.\n", present_parameters->BackBufferHeight);
608         }
609
610         if (present_parameters->BackBufferFormat == WINED3DFMT_UNKNOWN)
611         {
612             present_parameters->BackBufferFormat = swapchain->orig_fmt;
613             TRACE("Updating format to %s.\n", debug_d3dformat(swapchain->orig_fmt));
614         }
615     }
616     swapchain->presentParms = *present_parameters;
617
618     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
619             && present_parameters->BackBufferCount
620             && (present_parameters->BackBufferWidth != client_rect.right
621             || present_parameters->BackBufferHeight != client_rect.bottom))
622     {
623         TRACE("Rendering to FBO. Backbuffer %ux%u, window %ux%u.\n",
624                 present_parameters->BackBufferWidth,
625                 present_parameters->BackBufferHeight,
626                 client_rect.right, client_rect.bottom);
627         swapchain->render_to_fbo = TRUE;
628     }
629
630     TRACE("Creating front buffer.\n");
631     hr = IWineD3DDeviceParent_CreateRenderTarget(device->device_parent, parent,
632             swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
633             swapchain->presentParms.BackBufferFormat, swapchain->presentParms.MultiSampleType,
634             swapchain->presentParms.MultiSampleQuality, TRUE /* Lockable */,
635             (IWineD3DSurface **)&swapchain->front_buffer);
636     if (FAILED(hr))
637     {
638         WARN("Failed to create front buffer, hr %#x.\n", hr);
639         goto err;
640     }
641
642     surface_set_container(swapchain->front_buffer, WINED3D_CONTAINER_SWAPCHAIN, (IWineD3DBase *)swapchain);
643     if (surface_type == SURFACE_OPENGL)
644     {
645         surface_modify_location(swapchain->front_buffer, SFLAG_INDRAWABLE, TRUE);
646     }
647
648     /* MSDN says we're only allowed a single fullscreen swapchain per device,
649      * so we should really check to see if there is a fullscreen swapchain
650      * already. Does a single head count as full screen? */
651
652     if (!present_parameters->Windowed)
653     {
654         WINED3DDISPLAYMODE mode;
655
656         /* Change the display settings */
657         mode.Width = present_parameters->BackBufferWidth;
658         mode.Height = present_parameters->BackBufferHeight;
659         mode.Format = present_parameters->BackBufferFormat;
660         mode.RefreshRate = present_parameters->FullScreen_RefreshRateInHz;
661
662         hr = IWineD3DDevice_SetDisplayMode((IWineD3DDevice *)device, 0, &mode);
663         if (FAILED(hr))
664         {
665             WARN("Failed to set display mode, hr %#x.\n", hr);
666             goto err;
667         }
668         displaymode_set = TRUE;
669     }
670
671     swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(swapchain->context));
672     if (!swapchain->context)
673     {
674         ERR("Failed to create the context array.\n");
675         hr = E_OUTOFMEMORY;
676         goto err;
677     }
678     swapchain->num_contexts = 1;
679
680     if (surface_type == SURFACE_OPENGL)
681     {
682         static const enum wined3d_format_id formats[] =
683         {
684             WINED3DFMT_D24_UNORM_S8_UINT,
685             WINED3DFMT_D32_UNORM,
686             WINED3DFMT_R24_UNORM_X8_TYPELESS,
687             WINED3DFMT_D16_UNORM,
688             WINED3DFMT_S1_UINT_D15_UNORM
689         };
690
691         const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
692
693         /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
694          * You are able to add a depth + stencil surface at a later stage when you need it.
695          * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
696          * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
697          * context, need torecreate shaders, textures and other resources.
698          *
699          * The context manager already takes care of the state problem and for the other tasks code from Reset
700          * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
701          * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
702          * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
703          * issue needs to be fixed. */
704         for (i = 0; i < (sizeof(formats) / sizeof(*formats)); i++)
705         {
706             swapchain->ds_format = wined3d_get_format(gl_info, formats[i]);
707             swapchain->context[0] = context_create(swapchain, swapchain->front_buffer, swapchain->ds_format);
708             if (swapchain->context[0]) break;
709             TRACE("Depth stencil format %s is not supported, trying next format\n",
710                   debug_d3dformat(formats[i]));
711         }
712
713         if (!swapchain->context[0])
714         {
715             WARN("Failed to create context.\n");
716             hr = WINED3DERR_NOTAVAILABLE;
717             goto err;
718         }
719
720         if (!present_parameters->EnableAutoDepthStencil
721                 || swapchain->presentParms.AutoDepthStencilFormat != swapchain->ds_format->id)
722         {
723             FIXME("Add OpenGL context recreation support to context_validate_onscreen_formats\n");
724         }
725         context_release(swapchain->context[0]);
726     }
727     else
728     {
729         swapchain->context[0] = NULL;
730     }
731
732     if (swapchain->presentParms.BackBufferCount > 0)
733     {
734         swapchain->back_buffers = HeapAlloc(GetProcessHeap(), 0,
735                 sizeof(*swapchain->back_buffers) * swapchain->presentParms.BackBufferCount);
736         if (!swapchain->back_buffers)
737         {
738             ERR("Failed to allocate backbuffer array memory.\n");
739             hr = E_OUTOFMEMORY;
740             goto err;
741         }
742
743         for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
744         {
745             TRACE("Creating back buffer %u.\n", i);
746             hr = IWineD3DDeviceParent_CreateRenderTarget(device->device_parent, parent,
747                     swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
748                     swapchain->presentParms.BackBufferFormat, swapchain->presentParms.MultiSampleType,
749                     swapchain->presentParms.MultiSampleQuality, TRUE /* Lockable */,
750                     (IWineD3DSurface **)&swapchain->back_buffers[i]);
751             if (FAILED(hr))
752             {
753                 WARN("Failed to create back buffer %u, hr %#x.\n", i, hr);
754                 goto err;
755             }
756
757             surface_set_container(swapchain->back_buffers[i], WINED3D_CONTAINER_SWAPCHAIN, (IWineD3DBase *)swapchain);
758         }
759     }
760
761     /* Swapchains share the depth/stencil buffer, so only create a single depthstencil surface. */
762     if (present_parameters->EnableAutoDepthStencil && surface_type == SURFACE_OPENGL)
763     {
764         TRACE("Creating depth/stencil buffer.\n");
765         if (!device->auto_depth_stencil)
766         {
767             hr = IWineD3DDeviceParent_CreateDepthStencilSurface(device->device_parent,
768                     swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
769                     swapchain->presentParms.AutoDepthStencilFormat, swapchain->presentParms.MultiSampleType,
770                     swapchain->presentParms.MultiSampleQuality, FALSE /* FIXME: Discard */,
771                     (IWineD3DSurface **)&device->auto_depth_stencil);
772             if (FAILED(hr))
773             {
774                 WARN("Failed to create the auto depth stencil, hr %#x.\n", hr);
775                 goto err;
776             }
777
778             surface_set_container(device->auto_depth_stencil, WINED3D_CONTAINER_NONE, NULL);
779         }
780     }
781
782     IWineD3DSwapChain_GetGammaRamp((IWineD3DSwapChain *)swapchain, &swapchain->orig_gamma);
783
784     return WINED3D_OK;
785
786 err:
787     if (displaymode_set)
788     {
789         DEVMODEW devmode;
790
791         ClipCursor(NULL);
792
793         /* Change the display settings */
794         memset(&devmode, 0, sizeof(devmode));
795         devmode.dmSize = sizeof(devmode);
796         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
797         devmode.dmBitsPerPel = format->byte_count * CHAR_BIT;
798         devmode.dmPelsWidth = swapchain->orig_width;
799         devmode.dmPelsHeight = swapchain->orig_height;
800         ChangeDisplaySettingsExW(adapter->DeviceName, &devmode, NULL, CDS_FULLSCREEN, NULL);
801     }
802
803     if (swapchain->back_buffers)
804     {
805         for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
806         {
807             if (swapchain->back_buffers[i]) IWineD3DSurface_Release((IWineD3DSurface *)swapchain->back_buffers[i]);
808         }
809         HeapFree(GetProcessHeap(), 0, swapchain->back_buffers);
810     }
811
812     if (swapchain->context)
813     {
814         if (swapchain->context[0])
815         {
816             context_release(swapchain->context[0]);
817             context_destroy(device, swapchain->context[0]);
818             swapchain->num_contexts = 0;
819         }
820         HeapFree(GetProcessHeap(), 0, swapchain->context);
821     }
822
823     if (swapchain->front_buffer) IWineD3DSurface_Release((IWineD3DSurface *)swapchain->front_buffer);
824
825     return hr;
826 }
827
828 /* Do not call while under the GL lock. */
829 struct wined3d_context *swapchain_create_context_for_thread(IWineD3DSwapChain *iface)
830 {
831     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *) iface;
832     struct wined3d_context **newArray;
833     struct wined3d_context *ctx;
834
835     TRACE("Creating a new context for swapchain %p, thread %d\n", This, GetCurrentThreadId());
836
837     if (!(ctx = context_create(This, This->front_buffer, This->ds_format)))
838     {
839         ERR("Failed to create a new context for the swapchain\n");
840         return NULL;
841     }
842     context_release(ctx);
843
844     newArray = HeapAlloc(GetProcessHeap(), 0, sizeof(*newArray) * (This->num_contexts + 1));
845     if(!newArray) {
846         ERR("Out of memory when trying to allocate a new context array\n");
847         context_destroy(This->device, ctx);
848         return NULL;
849     }
850     memcpy(newArray, This->context, sizeof(*newArray) * This->num_contexts);
851     HeapFree(GetProcessHeap(), 0, This->context);
852     newArray[This->num_contexts] = ctx;
853     This->context = newArray;
854     This->num_contexts++;
855
856     TRACE("Returning context %p\n", ctx);
857     return ctx;
858 }
859
860 void get_drawable_size_swapchain(struct wined3d_context *context, UINT *width, UINT *height)
861 {
862     /* The drawable size of an onscreen drawable is the surface size.
863      * (Actually: The window size, but the surface is created in window size) */
864     *width = context->current_rt->currentDesc.Width;
865     *height = context->current_rt->currentDesc.Height;
866 }