Sync trunk.
[reactos.git] / dll / directx / wine / 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 /*IWineD3DSwapChain parts follow: */
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 IWineD3DSurface_SetContainer((IWineD3DSurface *)This->front_buffer, 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 IWineD3DSurface_SetContainer((IWineD3DSurface *)This->back_buffers[i], 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 == FALSE && This->presentParms.AutoRestoreDisplayMode) {
85 mode.Width = This->orig_width;
86 mode.Height = This->orig_height;
87 mode.RefreshRate = 0;
88 mode.Format = This->orig_fmt;
89 IWineD3DDevice_SetDisplayMode((IWineD3DDevice *)This->device, 0, &mode);
90 }
91
92 HeapFree(GetProcessHeap(), 0, This->context);
93 HeapFree(GetProcessHeap(), 0, This);
94 }
95
96 /* A GL context is provided by the caller */
97 static void swapchain_blit(IWineD3DSwapChainImpl *This, struct wined3d_context *context,
98 const RECT *src_rect, const RECT *dst_rect)
99 {
100 IWineD3DDeviceImpl *device = This->device;
101 IWineD3DSurfaceImpl *backbuffer = This->back_buffers[0];
102 UINT src_w = src_rect->right - src_rect->left;
103 UINT src_h = src_rect->bottom - src_rect->top;
104 GLenum gl_filter;
105 const struct wined3d_gl_info *gl_info = context->gl_info;
106 RECT win_rect;
107 UINT win_h;
108
109 TRACE("swapchain %p, context %p, src_rect %s, dst_rect %s.\n",
110 This, context, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect));
111
112 if (src_w == dst_rect->right - dst_rect->left && src_h == dst_rect->bottom - dst_rect->top)
113 gl_filter = GL_NEAREST;
114 else
115 gl_filter = GL_LINEAR;
116
117 GetClientRect(This->win_handle, &win_rect);
118 win_h = win_rect.bottom - win_rect.top;
119
120 if (gl_info->fbo_ops.glBlitFramebuffer && is_identity_fixup(backbuffer->resource.format_desc->color_fixup))
121 {
122 ENTER_GL();
123 context_apply_fbo_state_blit(context, GL_READ_FRAMEBUFFER, backbuffer, NULL);
124 glReadBuffer(GL_COLOR_ATTACHMENT0);
125
126 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, NULL);
127 context_set_draw_buffer(context, GL_BACK);
128
129 glDisable(GL_SCISSOR_TEST);
130 IWineD3DDeviceImpl_MarkStateDirty(This->device, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
131
132 /* Note that the texture is upside down */
133 gl_info->fbo_ops.glBlitFramebuffer(src_rect->left, src_rect->top, src_rect->right, src_rect->bottom,
134 dst_rect->left, win_h - dst_rect->top, dst_rect->right, win_h - dst_rect->bottom,
135 GL_COLOR_BUFFER_BIT, gl_filter);
136 checkGLcall("Swapchain present blit(EXT_framebuffer_blit)\n");
137 LEAVE_GL();
138 }
139 else
140 {
141 struct wined3d_context *context2;
142 float tex_left = src_rect->left;
143 float tex_top = src_rect->top;
144 float tex_right = src_rect->right;
145 float tex_bottom = src_rect->bottom;
146
147 context2 = context_acquire(This->device, This->back_buffers[0]);
148 context_apply_blit_state(context2, device);
149
150 if(backbuffer->Flags & SFLAG_NORMCOORD)
151 {
152 tex_left /= src_w;
153 tex_right /= src_w;
154 tex_top /= src_h;
155 tex_bottom /= src_h;
156 }
157
158 if (is_complex_fixup(backbuffer->resource.format_desc->color_fixup))
159 gl_filter = GL_NEAREST;
160
161 ENTER_GL();
162 context_bind_fbo(context2, GL_DRAW_FRAMEBUFFER, NULL);
163
164 /* Set up the texture. The surface is not in a IWineD3D*Texture container,
165 * so there are no d3d texture settings to dirtify
166 */
167 device->blitter->set_shader((IWineD3DDevice *) device, backbuffer);
168 glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MIN_FILTER, gl_filter);
169 glTexParameteri(backbuffer->texture_target, GL_TEXTURE_MAG_FILTER, gl_filter);
170
171 context_set_draw_buffer(context, GL_BACK);
172
173 /* Set the viewport to the destination rectandle, disable any projection
174 * transformation set up by context_apply_blit_state(), and draw a
175 * (-1,-1)-(1,1) quad.
176 *
177 * Back up viewport and matrix to avoid breaking last_was_blit
178 *
179 * Note that context_apply_blit_state() set up viewport and ortho to
180 * match the surface size - we want the GL drawable(=window) size. */
181 glPushAttrib(GL_VIEWPORT_BIT);
182 glViewport(dst_rect->left, win_h - dst_rect->bottom, dst_rect->right, win_h - dst_rect->top);
183 glMatrixMode(GL_PROJECTION);
184 glPushMatrix();
185 glLoadIdentity();
186
187 glBegin(GL_QUADS);
188 /* bottom left */
189 glTexCoord2f(tex_left, tex_bottom);
190 glVertex2i(-1, -1);
191
192 /* top left */
193 glTexCoord2f(tex_left, tex_top);
194 glVertex2i(-1, 1);
195
196 /* top right */
197 glTexCoord2f(tex_right, tex_top);
198 glVertex2i(1, 1);
199
200 /* bottom right */
201 glTexCoord2f(tex_right, tex_bottom);
202 glVertex2i(1, -1);
203 glEnd();
204
205 glPopMatrix();
206 glPopAttrib();
207
208 device->blitter->unset_shader((IWineD3DDevice *) device);
209 checkGLcall("Swapchain present blit(manual)\n");
210 LEAVE_GL();
211
212 context_release(context2);
213 }
214 }
215
216 static HRESULT WINAPI IWineD3DSwapChainImpl_Present(IWineD3DSwapChain *iface, CONST RECT *pSourceRect, CONST RECT *pDestRect, HWND hDestWindowOverride, CONST RGNDATA *pDirtyRegion, DWORD dwFlags) {
217 IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
218 const struct wined3d_gl_info *gl_info;
219 struct wined3d_context *context;
220 RECT src_rect, dst_rect;
221 BOOL render_to_fbo;
222 unsigned int sync;
223 int retval;
224
225 IWineD3DSwapChain_SetDestWindowOverride(iface, hDestWindowOverride);
226
227 context = context_acquire(This->device, This->back_buffers[0]);
228 if (!context->valid)
229 {
230 context_release(context);
231 WARN("Invalid context, skipping present.\n");
232 return WINED3D_OK;
233 }
234
235 gl_info = context->gl_info;
236
237 /* Render the cursor onto the back buffer, using our nifty directdraw blitting code :-) */
238 if (This->device->bCursorVisible && This->device->cursorTexture)
239 {
240 IWineD3DSurfaceImpl cursor;
241 RECT destRect =
242 {
243 This->device->xScreenSpace - This->device->xHotSpot,
244 This->device->yScreenSpace - This->device->yHotSpot,
245 This->device->xScreenSpace + This->device->cursorWidth - This->device->xHotSpot,
246 This->device->yScreenSpace + This->device->cursorHeight - This->device->yHotSpot,
247 };
248 TRACE("Rendering the cursor. Creating fake surface at %p\n", &cursor);
249 /* Build a fake surface to call the Blitting code. It is not possible to use the interface passed by
250 * the application because we are only supposed to copy the information out. Using a fake surface
251 * allows to use the Blitting engine and avoid copying the whole texture -> render target blitting code.
252 */
253 memset(&cursor, 0, sizeof(cursor));
254 cursor.lpVtbl = &IWineD3DSurface_Vtbl;
255 cursor.resource.ref = 1;
256 cursor.resource.device = This->device;
257 cursor.resource.pool = WINED3DPOOL_SCRATCH;
258 cursor.resource.format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
259 cursor.resource.resourceType = WINED3DRTYPE_SURFACE;
260 cursor.texture_name = This->device->cursorTexture;
261 cursor.texture_target = GL_TEXTURE_2D;
262 cursor.texture_level = 0;
263 cursor.currentDesc.Width = This->device->cursorWidth;
264 cursor.currentDesc.Height = This->device->cursorHeight;
265 /* The cursor must have pow2 sizes */
266 cursor.pow2Width = cursor.currentDesc.Width;
267 cursor.pow2Height = cursor.currentDesc.Height;
268 /* The surface is in the texture */
269 cursor.Flags |= SFLAG_INTEXTURE;
270 /* DDBLT_KEYSRC will cause BltOverride to enable the alpha test with GL_NOTEQUAL, 0.0,
271 * which is exactly what we want :-)
272 */
273 if (This->presentParms.Windowed) {
274 MapWindowPoints(NULL, This->win_handle, (LPPOINT)&destRect, 2);
275 }
276 IWineD3DSurface_Blt((IWineD3DSurface *)This->back_buffers[0], &destRect, (IWineD3DSurface *)&cursor,
277 NULL, WINEDDBLT_KEYSRC, NULL, WINED3DTEXF_POINT);
278 }
279
280 if (This->device->logo_surface)
281 {
282 /* Blit the logo into the upper left corner of the drawable. */
283 IWineD3DSurface_BltFast((IWineD3DSurface *)This->back_buffers[0], 0, 0,
284 This->device->logo_surface, NULL, WINEDDBLTFAST_SRCCOLORKEY);
285 }
286
287 TRACE("Presenting HDC %p.\n", context->hdc);
288
289 render_to_fbo = This->render_to_fbo;
290
291 if (pSourceRect)
292 {
293 src_rect = *pSourceRect;
294 if (!render_to_fbo && (src_rect.left || src_rect.top
295 || src_rect.right != This->presentParms.BackBufferWidth
296 || src_rect.bottom != This->presentParms.BackBufferHeight))
297 {
298 render_to_fbo = TRUE;
299 }
300 }
301 else
302 {
303 src_rect.left = 0;
304 src_rect.top = 0;
305 src_rect.right = This->presentParms.BackBufferWidth;
306 src_rect.bottom = This->presentParms.BackBufferHeight;
307 }
308
309 if (pDestRect) dst_rect = *pDestRect;
310 else GetClientRect(This->win_handle, &dst_rect);
311
312 if (!render_to_fbo && (dst_rect.left || dst_rect.top
313 || dst_rect.right != This->presentParms.BackBufferWidth
314 || dst_rect.bottom != This->presentParms.BackBufferHeight))
315 {
316 render_to_fbo = TRUE;
317 }
318
319 /* Rendering to a window of different size, presenting partial rectangles,
320 * or rendering to a different window needs help from FBO_blit or a textured
321 * draw. Render the swapchain to a FBO in the future.
322 *
323 * Note that FBO_blit from the backbuffer to the frontbuffer cannot solve
324 * all these issues - this fails if the window is smaller than the backbuffer.
325 */
326 if (!This->render_to_fbo && render_to_fbo && wined3d_settings.offscreen_rendering_mode == ORM_FBO)
327 {
328 IWineD3DSurface_LoadLocation((IWineD3DSurface *)This->back_buffers[0], SFLAG_INTEXTURE, NULL);
329 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)This->back_buffers[0], SFLAG_INDRAWABLE, FALSE);
330 This->render_to_fbo = TRUE;
331
332 /* Force the context manager to update the render target configuration next draw. */
333 context->current_rt = NULL;
334 }
335
336 if(This->render_to_fbo)
337 {
338 /* This codepath should only be hit with the COPY swapeffect. Otherwise a backbuffer-
339 * window size mismatch is impossible(fullscreen) and src and dst rectangles are
340 * not allowed(they need the COPY swapeffect)
341 *
342 * The DISCARD swap effect is ok as well since any backbuffer content is allowed after
343 * the swap
344 */
345 if(This->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP )
346 {
347 FIXME("Render-to-fbo with WINED3DSWAPEFFECT_FLIP\n");
348 }
349
350 swapchain_blit(This, context, &src_rect, &dst_rect);
351 }
352
353 if (This->num_contexts > 1) wglFinish();
354 SwapBuffers(context->hdc); /* TODO: cycle through the swapchain buffers */
355
356 TRACE("SwapBuffers called, Starting new frame\n");
357 /* FPS support */
358 if (TRACE_ON(fps))
359 {
360 DWORD time = GetTickCount();
361 This->frames++;
362 /* every 1.5 seconds */
363 if (time - This->prev_time > 1500) {
364 TRACE_(fps)("%p @ approx %.2ffps\n", This, 1000.0*This->frames/(time - This->prev_time));
365 This->prev_time = time;
366 This->frames = 0;
367 }
368 }
369
370 #if defined(FRAME_DEBUGGING)
371 {
372 if (GetFileAttributesA("C:\\D3DTRACE") != INVALID_FILE_ATTRIBUTES) {
373 if (!isOn) {
374 isOn = TRUE;
375 FIXME("Enabling D3D Trace\n");
376 __WINE_SET_DEBUGGING(__WINE_DBCL_TRACE, __wine_dbch_d3d, 1);
377 #if defined(SHOW_FRAME_MAKEUP)
378 FIXME("Singe Frame snapshots Starting\n");
379 isDumpingFrames = TRUE;
380 ENTER_GL();
381 glClear(GL_COLOR_BUFFER_BIT);
382 LEAVE_GL();
383 #endif
384
385 #if defined(SINGLE_FRAME_DEBUGGING)
386 } else {
387 #if defined(SHOW_FRAME_MAKEUP)
388 FIXME("Singe Frame snapshots Finishing\n");
389 isDumpingFrames = FALSE;
390 #endif
391 FIXME("Singe Frame trace complete\n");
392 DeleteFileA("C:\\D3DTRACE");
393 __WINE_SET_DEBUGGING(__WINE_DBCL_TRACE, __wine_dbch_d3d, 0);
394 #endif
395 }
396 } else {
397 if (isOn) {
398 isOn = FALSE;
399 #if defined(SHOW_FRAME_MAKEUP)
400 FIXME("Single Frame snapshots Finishing\n");
401 isDumpingFrames = FALSE;
402 #endif
403 FIXME("Disabling D3D Trace\n");
404 __WINE_SET_DEBUGGING(__WINE_DBCL_TRACE, __wine_dbch_d3d, 0);
405 }
406 }
407 }
408 #endif
409
410 /* This is disabled, but the code left in for debug purposes.
411 *
412 * Since we're allowed to modify the new back buffer on a D3DSWAPEFFECT_DISCARD flip,
413 * we can clear it with some ugly color to make bad drawing visible and ease debugging.
414 * The Debug runtime does the same on Windows. However, a few games do not redraw the
415 * screen properly, like Max Payne 2, which leaves a few pixels undefined.
416 *
417 * Tests show that the content of the back buffer after a discard flip is indeed not
418 * reliable, so no game can depend on the exact content. However, it resembles the
419 * old contents in some way, for example by showing fragments at other locations. In
420 * general, the color theme is still intact. So Max payne, which draws rather dark scenes
421 * gets a dark background image. If we clear it with a bright ugly color, the game's
422 * bug shows up much more than it does on Windows, and the players see single pixels
423 * with wrong colors.
424 * (The Max Payne bug has been confirmed on Windows with the debug runtime)
425 */
426 if (FALSE && This->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD) {
427 TRACE("Clearing the color buffer with cyan color\n");
428
429 IWineD3DDevice_Clear((IWineD3DDevice *)This->device, 0, NULL,
430 WINED3DCLEAR_TARGET, 0xff00ffff, 1.0f, 0);
431 }
432
433 if (!This->render_to_fbo && ((This->front_buffer->Flags & SFLAG_INSYSMEM)
434 || (This->back_buffers[0]->Flags & SFLAG_INSYSMEM)))
435 {
436 /* Both memory copies of the surfaces are ok, flip them around too instead of dirtifying
437 * Doesn't work with render_to_fbo because we're not flipping
438 */
439 IWineD3DSurfaceImpl *front = This->front_buffer;
440 IWineD3DSurfaceImpl *back = This->back_buffers[0];
441
442 if(front->resource.size == back->resource.size) {
443 DWORD fbflags;
444 flip_surface(front, back);
445
446 /* Tell the front buffer surface that is has been modified. However,
447 * the other locations were preserved during that, so keep the flags.
448 * This serves to update the emulated overlay, if any
449 */
450 fbflags = front->Flags;
451 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)front, SFLAG_INDRAWABLE, TRUE);
452 front->Flags = fbflags;
453 } else {
454 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) front, SFLAG_INDRAWABLE, TRUE);
455 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) back, SFLAG_INDRAWABLE, TRUE);
456 }
457 }
458 else
459 {
460 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)This->front_buffer, SFLAG_INDRAWABLE, TRUE);
461 /* If the swapeffect is DISCARD, the back buffer is undefined. That means the SYSMEM
462 * and INTEXTURE copies can keep their old content if they have any defined content.
463 * If the swapeffect is COPY, the content remains the same. If it is FLIP however,
464 * the texture / sysmem copy needs to be reloaded from the drawable
465 */
466 if (This->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP)
467 {
468 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)This->back_buffers[0], SFLAG_INDRAWABLE, TRUE);
469 }
470 }
471
472 if (This->device->depth_stencil)
473 {
474 if (This->presentParms.Flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
475 || This->device->depth_stencil->Flags & SFLAG_DISCARD)
476 {
477 surface_modify_ds_location(This->device->depth_stencil, SFLAG_DS_DISCARDED,
478 This->device->depth_stencil->currentDesc.Width,
479 This->device->depth_stencil->currentDesc.Height);
480 if (This->device->depth_stencil == This->device->onscreen_depth_stencil)
481 {
482 IWineD3DSurface_Release((IWineD3DSurface *)This->device->onscreen_depth_stencil);
483 This->device->onscreen_depth_stencil = NULL;
484 }
485 }
486 }
487
488 if (This->presentParms.PresentationInterval != WINED3DPRESENT_INTERVAL_IMMEDIATE
489 && gl_info->supported[SGI_VIDEO_SYNC])
490 {
491 retval = GL_EXTCALL(glXGetVideoSyncSGI(&sync));
492 if(retval != 0) {
493 ERR("glXGetVideoSyncSGI failed(retval = %d\n", retval);
494 }
495
496 switch(This->presentParms.PresentationInterval) {
497 case WINED3DPRESENT_INTERVAL_DEFAULT:
498 case WINED3DPRESENT_INTERVAL_ONE:
499 if(sync <= This->vSyncCounter) {
500 retval = GL_EXTCALL(glXWaitVideoSyncSGI(1, 0, &This->vSyncCounter));
501 } else {
502 This->vSyncCounter = sync;
503 }
504 break;
505 case WINED3DPRESENT_INTERVAL_TWO:
506 if(sync <= This->vSyncCounter + 1) {
507 retval = GL_EXTCALL(glXWaitVideoSyncSGI(2, This->vSyncCounter & 0x1, &This->vSyncCounter));
508 } else {
509 This->vSyncCounter = sync;
510 }
511 break;
512 case WINED3DPRESENT_INTERVAL_THREE:
513 if(sync <= This->vSyncCounter + 2) {
514 retval = GL_EXTCALL(glXWaitVideoSyncSGI(3, This->vSyncCounter % 0x3, &This->vSyncCounter));
515 } else {
516 This->vSyncCounter = sync;
517 }
518 break;
519 case WINED3DPRESENT_INTERVAL_FOUR:
520 if(sync <= This->vSyncCounter + 3) {
521 retval = GL_EXTCALL(glXWaitVideoSyncSGI(4, This->vSyncCounter & 0x3, &This->vSyncCounter));
522 } else {
523 This->vSyncCounter = sync;
524 }
525 break;
526 default:
527 FIXME("Unknown presentation interval %08x\n", This->presentParms.PresentationInterval);
528 }
529 }
530
531 context_release(context);
532
533 TRACE("returning\n");
534 return WINED3D_OK;
535 }
536
537 static HRESULT WINAPI IWineD3DSwapChainImpl_SetDestWindowOverride(IWineD3DSwapChain *iface, HWND window)
538 {
539 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)iface;
540
541 if (!window) window = swapchain->device_window;
542 if (window == swapchain->win_handle) return WINED3D_OK;
543
544 TRACE("Setting swapchain %p window from %p to %p\n", swapchain, swapchain->win_handle, window);
545 swapchain->win_handle = window;
546
547 return WINED3D_OK;
548 }
549
550 static const IWineD3DSwapChainVtbl IWineD3DSwapChain_Vtbl =
551 {
552 /* IUnknown */
553 IWineD3DBaseSwapChainImpl_QueryInterface,
554 IWineD3DBaseSwapChainImpl_AddRef,
555 IWineD3DBaseSwapChainImpl_Release,
556 /* IWineD3DSwapChain */
557 IWineD3DBaseSwapChainImpl_GetParent,
558 IWineD3DSwapChainImpl_Destroy,
559 IWineD3DBaseSwapChainImpl_GetDevice,
560 IWineD3DSwapChainImpl_Present,
561 IWineD3DSwapChainImpl_SetDestWindowOverride,
562 IWineD3DBaseSwapChainImpl_GetFrontBufferData,
563 IWineD3DBaseSwapChainImpl_GetBackBuffer,
564 IWineD3DBaseSwapChainImpl_GetRasterStatus,
565 IWineD3DBaseSwapChainImpl_GetDisplayMode,
566 IWineD3DBaseSwapChainImpl_GetPresentParameters,
567 IWineD3DBaseSwapChainImpl_SetGammaRamp,
568 IWineD3DBaseSwapChainImpl_GetGammaRamp
569 };
570
571 static LONG fullscreen_style(LONG style)
572 {
573 /* Make sure the window is managed, otherwise we won't get keyboard input. */
574 style |= WS_POPUP | WS_SYSMENU;
575 style &= ~(WS_CAPTION | WS_THICKFRAME);
576
577 return style;
578 }
579
580 static LONG fullscreen_exstyle(LONG exstyle)
581 {
582 /* Filter out window decorations. */
583 exstyle &= ~(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
584
585 return exstyle;
586 }
587
588 void swapchain_setup_fullscreen_window(IWineD3DSwapChainImpl *swapchain, UINT w, UINT h)
589 {
590 IWineD3DDeviceImpl *device = swapchain->device;
591 HWND window = swapchain->device_window;
592 BOOL filter_messages;
593 LONG style, exstyle;
594
595 TRACE("Setting up window %p for fullscreen mode.\n", window);
596
597 if (device->style || device->exStyle)
598 {
599 ERR("Changing the window style for window %p, but another style (%08x, %08x) is already stored.\n",
600 window, device->style, device->exStyle);
601 }
602
603 device->style = GetWindowLongW(window, GWL_STYLE);
604 device->exStyle = GetWindowLongW(window, GWL_EXSTYLE);
605
606 style = fullscreen_style(device->style);
607 exstyle = fullscreen_exstyle(device->exStyle);
608
609 TRACE("Old style was %08x, %08x, setting to %08x, %08x.\n",
610 device->style, device->exStyle, style, exstyle);
611
612 filter_messages = device->filter_messages;
613 device->filter_messages = TRUE;
614
615 SetWindowLongW(window, GWL_STYLE, style);
616 SetWindowLongW(window, GWL_EXSTYLE, exstyle);
617 SetWindowPos(window, HWND_TOP, 0, 0, w, h, SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOACTIVATE);
618
619 device->filter_messages = filter_messages;
620 }
621
622 void swapchain_restore_fullscreen_window(IWineD3DSwapChainImpl *swapchain)
623 {
624 IWineD3DDeviceImpl *device = swapchain->device;
625 HWND window = swapchain->device_window;
626 BOOL filter_messages;
627 LONG style, exstyle;
628
629 if (!device->style && !device->exStyle) return;
630
631 TRACE("Restoring window style of window %p to %08x, %08x.\n",
632 window, device->style, device->exStyle);
633
634 style = GetWindowLongW(window, GWL_STYLE);
635 exstyle = GetWindowLongW(window, GWL_EXSTYLE);
636
637 filter_messages = device->filter_messages;
638 device->filter_messages = TRUE;
639
640 /* Only restore the style if the application didn't modify it during the
641 * fullscreen phase. Some applications change it before calling Reset()
642 * when switching between windowed and fullscreen modes (HL2), some
643 * depend on the original style (Eve Online). */
644 if (style == fullscreen_style(device->style) && exstyle == fullscreen_exstyle(device->exStyle))
645 {
646 SetWindowLongW(window, GWL_STYLE, device->style);
647 SetWindowLongW(window, GWL_EXSTYLE, device->exStyle);
648 }
649 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
650
651 device->filter_messages = filter_messages;
652
653 /* Delete the old values. */
654 device->style = 0;
655 device->exStyle = 0;
656 }
657
658
659 HRESULT swapchain_init(IWineD3DSwapChainImpl *swapchain, WINED3DSURFTYPE surface_type,
660 IWineD3DDeviceImpl *device, WINED3DPRESENT_PARAMETERS *present_parameters, IUnknown *parent)
661 {
662 const struct wined3d_adapter *adapter = device->adapter;
663 const struct wined3d_format_desc *format_desc;
664 BOOL displaymode_set = FALSE;
665 WINED3DDISPLAYMODE mode;
666 RECT client_rect;
667 HWND window;
668 HRESULT hr;
669 UINT i;
670
671 if (present_parameters->BackBufferCount > WINED3DPRESENT_BACK_BUFFER_MAX)
672 {
673 FIXME("The application requested %u back buffers, this is not supported.\n",
674 present_parameters->BackBufferCount);
675 return WINED3DERR_INVALIDCALL;
676 }
677
678 if (present_parameters->BackBufferCount > 1)
679 {
680 FIXME("The application requested more than one back buffer, this is not properly supported.\n"
681 "Please configure the application to use double buffering (1 back buffer) if possible.\n");
682 }
683
684 switch (surface_type)
685 {
686 case SURFACE_GDI:
687 swapchain->lpVtbl = &IWineGDISwapChain_Vtbl;
688 break;
689
690 case SURFACE_OPENGL:
691 swapchain->lpVtbl = &IWineD3DSwapChain_Vtbl;
692 break;
693
694 case SURFACE_UNKNOWN:
695 FIXME("Caller tried to create a SURFACE_UNKNOWN swapchain.\n");
696 return WINED3DERR_INVALIDCALL;
697 }
698
699 window = present_parameters->hDeviceWindow ? present_parameters->hDeviceWindow : device->createParms.hFocusWindow;
700
701 swapchain->device = device;
702 swapchain->parent = parent;
703 swapchain->ref = 1;
704 swapchain->win_handle = window;
705 swapchain->device_window = window;
706
707 if (!present_parameters->Windowed && window)
708 {
709 swapchain_setup_fullscreen_window(swapchain, present_parameters->BackBufferWidth,
710 present_parameters->BackBufferHeight);
711 }
712
713 IWineD3D_GetAdapterDisplayMode(device->wined3d, adapter->ordinal, &mode);
714 swapchain->orig_width = mode.Width;
715 swapchain->orig_height = mode.Height;
716 swapchain->orig_fmt = mode.Format;
717 format_desc = getFormatDescEntry(mode.Format, &adapter->gl_info);
718
719 GetClientRect(window, &client_rect);
720 if (present_parameters->Windowed
721 && (!present_parameters->BackBufferWidth || !present_parameters->BackBufferHeight
722 || present_parameters->BackBufferFormat == WINED3DFMT_UNKNOWN))
723 {
724
725 if (!present_parameters->BackBufferWidth)
726 {
727 present_parameters->BackBufferWidth = client_rect.right;
728 TRACE("Updating width to %u.\n", present_parameters->BackBufferWidth);
729 }
730
731 if (!present_parameters->BackBufferHeight)
732 {
733 present_parameters->BackBufferHeight = client_rect.bottom;
734 TRACE("Updating height to %u.\n", present_parameters->BackBufferHeight);
735 }
736
737 if (present_parameters->BackBufferFormat == WINED3DFMT_UNKNOWN)
738 {
739 present_parameters->BackBufferFormat = swapchain->orig_fmt;
740 TRACE("Updating format to %s.\n", debug_d3dformat(swapchain->orig_fmt));
741 }
742 }
743 swapchain->presentParms = *present_parameters;
744
745 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
746 && present_parameters->BackBufferCount
747 && (present_parameters->BackBufferWidth != client_rect.right
748 || present_parameters->BackBufferHeight != client_rect.bottom))
749 {
750 TRACE("Rendering to FBO. Backbuffer %ux%u, window %ux%u.\n",
751 present_parameters->BackBufferWidth,
752 present_parameters->BackBufferHeight,
753 client_rect.right, client_rect.bottom);
754 swapchain->render_to_fbo = TRUE;
755 }
756
757 TRACE("Creating front buffer.\n");
758 hr = IWineD3DDeviceParent_CreateRenderTarget(device->device_parent, parent,
759 swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
760 swapchain->presentParms.BackBufferFormat, swapchain->presentParms.MultiSampleType,
761 swapchain->presentParms.MultiSampleQuality, TRUE /* Lockable */,
762 (IWineD3DSurface **)&swapchain->front_buffer);
763 if (FAILED(hr))
764 {
765 WARN("Failed to create front buffer, hr %#x.\n", hr);
766 goto err;
767 }
768
769 IWineD3DSurface_SetContainer((IWineD3DSurface *)swapchain->front_buffer, (IWineD3DBase *)swapchain);
770 swapchain->front_buffer->Flags |= SFLAG_SWAPCHAIN;
771 if (surface_type == SURFACE_OPENGL)
772 {
773 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)swapchain->front_buffer, SFLAG_INDRAWABLE, TRUE);
774 }
775
776 /* MSDN says we're only allowed a single fullscreen swapchain per device,
777 * so we should really check to see if there is a fullscreen swapchain
778 * already. Does a single head count as full screen? */
779
780 if (!present_parameters->Windowed)
781 {
782 WINED3DDISPLAYMODE mode;
783
784 /* Change the display settings */
785 mode.Width = present_parameters->BackBufferWidth;
786 mode.Height = present_parameters->BackBufferHeight;
787 mode.Format = present_parameters->BackBufferFormat;
788 mode.RefreshRate = present_parameters->FullScreen_RefreshRateInHz;
789
790 hr = IWineD3DDevice_SetDisplayMode((IWineD3DDevice *)device, 0, &mode);
791 if (FAILED(hr))
792 {
793 WARN("Failed to set display mode, hr %#x.\n", hr);
794 goto err;
795 }
796 displaymode_set = TRUE;
797 }
798
799 swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(swapchain->context));
800 if (!swapchain->context)
801 {
802 ERR("Failed to create the context array.\n");
803 hr = E_OUTOFMEMORY;
804 goto err;
805 }
806 swapchain->num_contexts = 1;
807
808 if (surface_type == SURFACE_OPENGL)
809 {
810 WINED3DFORMAT formats[] =
811 {
812 WINED3DFMT_D24_UNORM_S8_UINT,
813 WINED3DFMT_D32_UNORM,
814 WINED3DFMT_R24_UNORM_X8_TYPELESS,
815 WINED3DFMT_D16_UNORM,
816 WINED3DFMT_S1_UINT_D15_UNORM
817 };
818
819 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
820
821 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
822 * You are able to add a depth + stencil surface at a later stage when you need it.
823 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
824 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
825 * context, need torecreate shaders, textures and other resources.
826 *
827 * The context manager already takes care of the state problem and for the other tasks code from Reset
828 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
829 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
830 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
831 * issue needs to be fixed. */
832 for (i = 0; i < (sizeof(formats) / sizeof(*formats)); i++)
833 {
834 swapchain->ds_format = getFormatDescEntry(formats[i], gl_info);
835 swapchain->context[0] = context_create(swapchain, swapchain->front_buffer, swapchain->ds_format);
836 if (swapchain->context[0]) break;
837 TRACE("Depth stencil format %s is not supported, trying next format\n",
838 debug_d3dformat(formats[i]));
839 }
840
841 if (!swapchain->context[0])
842 {
843 WARN("Failed to create context.\n");
844 hr = WINED3DERR_NOTAVAILABLE;
845 goto err;
846 }
847
848 if (!present_parameters->EnableAutoDepthStencil
849 || swapchain->presentParms.AutoDepthStencilFormat != swapchain->ds_format->format)
850 {
851 FIXME("Add OpenGL context recreation support to context_validate_onscreen_formats\n");
852 }
853 context_release(swapchain->context[0]);
854 }
855 else
856 {
857 swapchain->context[0] = NULL;
858 }
859
860 if (swapchain->presentParms.BackBufferCount > 0)
861 {
862 swapchain->back_buffers = HeapAlloc(GetProcessHeap(), 0,
863 sizeof(*swapchain->back_buffers) * swapchain->presentParms.BackBufferCount);
864 if (!swapchain->back_buffers)
865 {
866 ERR("Failed to allocate backbuffer array memory.\n");
867 hr = E_OUTOFMEMORY;
868 goto err;
869 }
870
871 for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
872 {
873 TRACE("Creating back buffer %u.\n", i);
874 hr = IWineD3DDeviceParent_CreateRenderTarget(device->device_parent, parent,
875 swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
876 swapchain->presentParms.BackBufferFormat, swapchain->presentParms.MultiSampleType,
877 swapchain->presentParms.MultiSampleQuality, TRUE /* Lockable */,
878 (IWineD3DSurface **)&swapchain->back_buffers[i]);
879 if (FAILED(hr))
880 {
881 WARN("Failed to create back buffer %u, hr %#x.\n", i, hr);
882 goto err;
883 }
884
885 IWineD3DSurface_SetContainer((IWineD3DSurface *)swapchain->back_buffers[i], (IWineD3DBase *)swapchain);
886 swapchain->back_buffers[i]->Flags |= SFLAG_SWAPCHAIN;
887 }
888 }
889
890 /* Swapchains share the depth/stencil buffer, so only create a single depthstencil surface. */
891 if (present_parameters->EnableAutoDepthStencil && surface_type == SURFACE_OPENGL)
892 {
893 TRACE("Creating depth/stencil buffer.\n");
894 if (!device->auto_depth_stencil)
895 {
896 hr = IWineD3DDeviceParent_CreateDepthStencilSurface(device->device_parent, parent,
897 swapchain->presentParms.BackBufferWidth, swapchain->presentParms.BackBufferHeight,
898 swapchain->presentParms.AutoDepthStencilFormat, swapchain->presentParms.MultiSampleType,
899 swapchain->presentParms.MultiSampleQuality, FALSE /* FIXME: Discard */,
900 (IWineD3DSurface **)&device->auto_depth_stencil);
901 if (FAILED(hr))
902 {
903 WARN("Failed to create the auto depth stencil, hr %#x.\n", hr);
904 goto err;
905 }
906
907 IWineD3DSurface_SetContainer((IWineD3DSurface *)device->auto_depth_stencil, NULL);
908 }
909 }
910
911 IWineD3DSwapChain_GetGammaRamp((IWineD3DSwapChain *)swapchain, &swapchain->orig_gamma);
912
913 return WINED3D_OK;
914
915 err:
916 if (displaymode_set)
917 {
918 DEVMODEW devmode;
919
920 ClipCursor(NULL);
921
922 /* Change the display settings */
923 memset(&devmode, 0, sizeof(devmode));
924 devmode.dmSize = sizeof(devmode);
925 devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
926 devmode.dmBitsPerPel = format_desc->byte_count * 8;
927 devmode.dmPelsWidth = swapchain->orig_width;
928 devmode.dmPelsHeight = swapchain->orig_height;
929 ChangeDisplaySettingsExW(adapter->DeviceName, &devmode, NULL, CDS_FULLSCREEN, NULL);
930 }
931
932 if (swapchain->back_buffers)
933 {
934 for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
935 {
936 if (swapchain->back_buffers[i]) IWineD3DSurface_Release((IWineD3DSurface *)swapchain->back_buffers[i]);
937 }
938 HeapFree(GetProcessHeap(), 0, swapchain->back_buffers);
939 }
940
941 if (swapchain->context)
942 {
943 if (swapchain->context[0])
944 {
945 context_release(swapchain->context[0]);
946 context_destroy(device, swapchain->context[0]);
947 swapchain->num_contexts = 0;
948 }
949 HeapFree(GetProcessHeap(), 0, swapchain->context);
950 }
951
952 if (swapchain->front_buffer) IWineD3DSurface_Release((IWineD3DSurface *)swapchain->front_buffer);
953
954 return hr;
955 }
956
957 struct wined3d_context *swapchain_create_context_for_thread(IWineD3DSwapChain *iface)
958 {
959 IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *) iface;
960 struct wined3d_context **newArray;
961 struct wined3d_context *ctx;
962
963 TRACE("Creating a new context for swapchain %p, thread %d\n", This, GetCurrentThreadId());
964
965 if (!(ctx = context_create(This, This->front_buffer, This->ds_format)))
966 {
967 ERR("Failed to create a new context for the swapchain\n");
968 return NULL;
969 }
970 context_release(ctx);
971
972 newArray = HeapAlloc(GetProcessHeap(), 0, sizeof(*newArray) * This->num_contexts + 1);
973 if(!newArray) {
974 ERR("Out of memory when trying to allocate a new context array\n");
975 context_destroy(This->device, ctx);
976 return NULL;
977 }
978 memcpy(newArray, This->context, sizeof(*newArray) * This->num_contexts);
979 HeapFree(GetProcessHeap(), 0, This->context);
980 newArray[This->num_contexts] = ctx;
981 This->context = newArray;
982 This->num_contexts++;
983
984 TRACE("Returning context %p\n", ctx);
985 return ctx;
986 }
987
988 void get_drawable_size_swapchain(struct wined3d_context *context, UINT *width, UINT *height)
989 {
990 /* The drawable size of an onscreen drawable is the surface size.
991 * (Actually: The window size, but the surface is created in window size) */
992 *width = context->current_rt->currentDesc.Width;
993 *height = context->current_rt->currentDesc.Height;
994 }