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