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