wined3d: Allow shader_buffer_init() to fail.
[wine] / dlls / wined3d / swapchain.c
1 /*
2  *IDirect3DSwapChain9 implementation
3  *
4  *Copyright 2002-2003 Jason Edmeades
5  *Copyright 2002-2003 Raphael Junqueira
6  *Copyright 2005 Oliver Stieber
7  *Copyright 2007-2008 Stefan Dösinger for CodeWeavers
8  *
9  *This library is free software; you can redistribute it and/or
10  *modify it under the terms of the GNU Lesser General Public
11  *License as published by the Free Software Foundation; either
12  *version 2.1 of the License, or (at your option) any later version.
13  *
14  *This library is distributed in the hope that it will be useful,
15  *but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  *Lesser General Public License for more details.
18  *
19  *You should have received a copy of the GNU Lesser General Public
20  *License along with this library; if not, write to the Free Software
21  *Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include "config.h"
25 #include "wined3d_private.h"
26
27
28 /*TODO: some of the additional parameters may be required to
29     set the gamma ramp (for some weird reason microsoft have left swap gammaramp in device
30     but it operates on a swapchain, it may be a good idea to move it to IWineD3DSwapChain for IWineD3D)*/
31
32
33 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
34 WINE_DECLARE_DEBUG_CHANNEL(fps);
35
36 #define GLINFO_LOCATION This->wineD3DDevice->adapter->gl_info
37
38 /*IWineD3DSwapChain parts follow: */
39 static void WINAPI IWineD3DSwapChainImpl_Destroy(IWineD3DSwapChain *iface, D3DCB_DESTROYSURFACEFN D3DCB_DestroyRenderTarget) {
40     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
41     WINED3DDISPLAYMODE mode;
42     unsigned int i;
43
44     TRACE("Destroying swapchain %p\n", iface);
45
46     IWineD3DSwapChain_SetGammaRamp(iface, 0, &This->orig_gamma);
47
48     /* release the ref to the front and back buffer parents */
49     if(This->frontBuffer) {
50         IWineD3DSurface_SetContainer(This->frontBuffer, 0);
51         if(D3DCB_DestroyRenderTarget(This->frontBuffer) > 0) {
52             FIXME("(%p) Something's still holding the front buffer\n",This);
53         }
54     }
55
56     if(This->backBuffer) {
57         UINT i;
58         for(i = 0; i < This->presentParms.BackBufferCount; i++) {
59             IWineD3DSurface_SetContainer(This->backBuffer[i], 0);
60             if(D3DCB_DestroyRenderTarget(This->backBuffer[i]) > 0) {
61                 FIXME("(%p) Something's still holding the back buffer\n",This);
62             }
63         }
64         HeapFree(GetProcessHeap(), 0, This->backBuffer);
65     }
66
67     for (i = 0; i < This->num_contexts; ++i)
68     {
69         if (This->context[i] == This->wineD3DDevice->activeContext)
70         {
71             IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)This->wineD3DDevice->swapchains[0];
72
73             /* Avoid destroying the currently active context for non-implicit swapchains. */
74             if (This != swapchain)
75             {
76                 TRACE("Would destroy currently active context %p on a non-implicit swapchain.\n", This->context[i]);
77
78                 if (swapchain->backBuffer)
79                     ActivateContext(This->wineD3DDevice, swapchain->backBuffer[0], CTXUSAGE_RESOURCELOAD);
80                 else
81                     ActivateContext(This->wineD3DDevice, swapchain->frontBuffer, CTXUSAGE_RESOURCELOAD);
82             }
83         }
84
85         DestroyContext(This->wineD3DDevice, This->context[i]);
86     }
87     /* Restore the screen resolution if we rendered in fullscreen
88      * This will restore the screen resolution to what it was before creating the swapchain. In case of d3d8 and d3d9
89      * this will be the original desktop resolution. In case of d3d7 this will be a NOP because ddraw sets the resolution
90      * before starting up Direct3D, thus orig_width and orig_height will be equal to the modes in the presentation params
91      */
92     if(This->presentParms.Windowed == FALSE && This->presentParms.AutoRestoreDisplayMode) {
93         mode.Width = This->orig_width;
94         mode.Height = This->orig_height;
95         mode.RefreshRate = 0;
96         mode.Format = This->orig_fmt;
97         IWineD3DDevice_SetDisplayMode((IWineD3DDevice *) This->wineD3DDevice, 0, &mode);
98     }
99     HeapFree(GetProcessHeap(), 0, This->context);
100
101     HeapFree(GetProcessHeap(), 0, This);
102 }
103
104 static HRESULT WINAPI IWineD3DSwapChainImpl_Present(IWineD3DSwapChain *iface, CONST RECT *pSourceRect, CONST RECT *pDestRect, HWND hDestWindowOverride, CONST RGNDATA *pDirtyRegion, DWORD dwFlags) {
105     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
106     unsigned int sync;
107     int retval;
108
109
110     ActivateContext(This->wineD3DDevice, This->backBuffer[0], CTXUSAGE_RESOURCELOAD);
111
112     /* Render the cursor onto the back buffer, using our nifty directdraw blitting code :-) */
113     if(This->wineD3DDevice->bCursorVisible && This->wineD3DDevice->cursorTexture) {
114         IWineD3DSurfaceImpl cursor;
115         RECT destRect = {This->wineD3DDevice->xScreenSpace - This->wineD3DDevice->xHotSpot,
116                          This->wineD3DDevice->yScreenSpace - This->wineD3DDevice->yHotSpot,
117                          This->wineD3DDevice->xScreenSpace + This->wineD3DDevice->cursorWidth - This->wineD3DDevice->xHotSpot,
118                          This->wineD3DDevice->yScreenSpace + This->wineD3DDevice->cursorHeight - This->wineD3DDevice->yHotSpot};
119         TRACE("Rendering the cursor. Creating fake surface at %p\n", &cursor);
120         /* Build a fake surface to call the Blitting code. It is not possible to use the interface passed by
121          * the application because we are only supposed to copy the information out. Using a fake surface
122          * allows to use the Blitting engine and avoid copying the whole texture -> render target blitting code.
123          */
124         memset(&cursor, 0, sizeof(cursor));
125         cursor.lpVtbl = &IWineD3DSurface_Vtbl;
126         cursor.resource.ref = 1;
127         cursor.resource.wineD3DDevice = This->wineD3DDevice;
128         cursor.resource.pool = WINED3DPOOL_SCRATCH;
129         cursor.resource.format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->wineD3DDevice->adapter->gl_info);
130         cursor.resource.resourceType = WINED3DRTYPE_SURFACE;
131         cursor.glDescription.textureName = This->wineD3DDevice->cursorTexture;
132         cursor.glDescription.target = GL_TEXTURE_2D;
133         cursor.glDescription.level = 0;
134         cursor.currentDesc.Width = This->wineD3DDevice->cursorWidth;
135         cursor.currentDesc.Height = This->wineD3DDevice->cursorHeight;
136         cursor.glRect.left = 0;
137         cursor.glRect.top = 0;
138         cursor.glRect.right = cursor.currentDesc.Width;
139         cursor.glRect.bottom = cursor.currentDesc.Height;
140         /* The cursor must have pow2 sizes */
141         cursor.pow2Width = cursor.currentDesc.Width;
142         cursor.pow2Height = cursor.currentDesc.Height;
143         /* The surface is in the texture */
144         cursor.Flags |= SFLAG_INTEXTURE;
145         /* DDBLT_KEYSRC will cause BltOverride to enable the alpha test with GL_NOTEQUAL, 0.0,
146          * which is exactly what we want :-)
147          */
148         if (This->presentParms.Windowed) {
149             MapWindowPoints(NULL, This->win_handle, (LPPOINT)&destRect, 2);
150         }
151         IWineD3DSurface_Blt(This->backBuffer[0], &destRect, (IWineD3DSurface *) &cursor, NULL, WINEDDBLT_KEYSRC, NULL, WINED3DTEXF_NONE);
152     }
153     if(This->wineD3DDevice->logo_surface) {
154         /* Blit the logo into the upper left corner of the drawable */
155         IWineD3DSurface_BltFast(This->backBuffer[0], 0, 0, This->wineD3DDevice->logo_surface, NULL, WINEDDBLTFAST_SRCCOLORKEY);
156     }
157
158     if (pSourceRect || pDestRect) FIXME("Unhandled present rects %s/%s\n", wine_dbgstr_rect(pSourceRect), wine_dbgstr_rect(pDestRect));
159     /* TODO: If only source rect or dest rect are supplied then clip the window to match */
160     TRACE("presetting HDC %p\n", This->context[0]->hdc);
161
162     /* Don't call checkGLcall, as glGetError is not applicable here */
163     if (hDestWindowOverride && This->win_handle != hDestWindowOverride) {
164         IWineD3DSwapChain_SetDestWindowOverride(iface, hDestWindowOverride);
165     }
166
167     SwapBuffers(This->context[0]->hdc); /* TODO: cycle through the swapchain buffers */
168
169     TRACE("SwapBuffers called, Starting new frame\n");
170     /* FPS support */
171     if (TRACE_ON(fps))
172     {
173         DWORD time = GetTickCount();
174         This->frames++;
175         /* every 1.5 seconds */
176         if (time - This->prev_time > 1500) {
177             TRACE_(fps)("%p @ approx %.2ffps\n", This, 1000.0*This->frames/(time - This->prev_time));
178             This->prev_time = time;
179             This->frames = 0;
180         }
181     }
182
183 #if defined(FRAME_DEBUGGING)
184 {
185     if (GetFileAttributesA("C:\\D3DTRACE") != INVALID_FILE_ATTRIBUTES) {
186         if (!isOn) {
187             isOn = TRUE;
188             FIXME("Enabling D3D Trace\n");
189             __WINE_SET_DEBUGGING(__WINE_DBCL_TRACE, __wine_dbch_d3d, 1);
190 #if defined(SHOW_FRAME_MAKEUP)
191             FIXME("Singe Frame snapshots Starting\n");
192             isDumpingFrames = TRUE;
193             ENTER_GL();
194             glClear(GL_COLOR_BUFFER_BIT);
195             LEAVE_GL();
196 #endif
197
198 #if defined(SINGLE_FRAME_DEBUGGING)
199         } else {
200 #if defined(SHOW_FRAME_MAKEUP)
201             FIXME("Singe Frame snapshots Finishing\n");
202             isDumpingFrames = FALSE;
203 #endif
204             FIXME("Singe Frame trace complete\n");
205             DeleteFileA("C:\\D3DTRACE");
206             __WINE_SET_DEBUGGING(__WINE_DBCL_TRACE, __wine_dbch_d3d, 0);
207 #endif
208         }
209     } else {
210         if (isOn) {
211             isOn = FALSE;
212 #if defined(SHOW_FRAME_MAKEUP)
213             FIXME("Single Frame snapshots Finishing\n");
214             isDumpingFrames = FALSE;
215 #endif
216             FIXME("Disabling D3D Trace\n");
217             __WINE_SET_DEBUGGING(__WINE_DBCL_TRACE, __wine_dbch_d3d, 0);
218         }
219     }
220 }
221 #endif
222
223     /* This is disabled, but the code left in for debug purposes.
224      *
225      * Since we're allowed to modify the new back buffer on a D3DSWAPEFFECT_DISCARD flip,
226      * we can clear it with some ugly color to make bad drawing visible and ease debugging.
227      * The Debug runtime does the same on Windows. However, a few games do not redraw the
228      * screen properly, like Max Payne 2, which leaves a few pixels undefined.
229      *
230      * Tests show that the content of the back buffer after a discard flip is indeed not
231      * reliable, so no game can depend on the exact content. However, it resembles the
232      * old contents in some way, for example by showing fragments at other locations. In
233      * general, the color theme is still intact. So Max payne, which draws rather dark scenes
234      * gets a dark background image. If we clear it with a bright ugly color, the game's
235      * bug shows up much more than it does on Windows, and the players see single pixels
236      * with wrong colors.
237      * (The Max Payne bug has been confirmed on Windows with the debug runtime)
238      */
239     if (FALSE && This->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD) {
240         TRACE("Clearing the color buffer with cyan color\n");
241
242         IWineD3DDevice_Clear((IWineD3DDevice*)This->wineD3DDevice, 0, NULL,
243                 WINED3DCLEAR_TARGET, 0xff00ffff, 1.0f, 0);
244     }
245
246     if(((IWineD3DSurfaceImpl *) This->frontBuffer)->Flags   & SFLAG_INSYSMEM ||
247        ((IWineD3DSurfaceImpl *) This->backBuffer[0])->Flags & SFLAG_INSYSMEM ) {
248         /* Both memory copies of the surfaces are ok, flip them around too instead of dirtifying */
249         IWineD3DSurfaceImpl *front = (IWineD3DSurfaceImpl *) This->frontBuffer;
250         IWineD3DSurfaceImpl *back = (IWineD3DSurfaceImpl *) This->backBuffer[0];
251
252         if(front->resource.size == back->resource.size) {
253             DWORD fbflags;
254             flip_surface(front, back);
255
256             /* Tell the front buffer surface that is has been modified. However,
257              * the other locations were preserved during that, so keep the flags.
258              * This serves to update the emulated overlay, if any
259              */
260             fbflags = front->Flags;
261             IWineD3DSurface_ModifyLocation(This->frontBuffer, SFLAG_INDRAWABLE, TRUE);
262             front->Flags = fbflags;
263         } else {
264             IWineD3DSurface_ModifyLocation((IWineD3DSurface *) front, SFLAG_INDRAWABLE, TRUE);
265             IWineD3DSurface_ModifyLocation((IWineD3DSurface *) back, SFLAG_INDRAWABLE, TRUE);
266         }
267     } else {
268         IWineD3DSurface_ModifyLocation(This->frontBuffer, SFLAG_INDRAWABLE, TRUE);
269         /* If the swapeffect is DISCARD, the back buffer is undefined. That means the SYSMEM
270          * and INTEXTURE copies can keep their old content if they have any defined content.
271          * If the swapeffect is COPY, the content remains the same. If it is FLIP however,
272          * the texture / sysmem copy needs to be reloaded from the drawable
273          */
274         if(This->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP) {
275             IWineD3DSurface_ModifyLocation(This->backBuffer[0], SFLAG_INDRAWABLE, TRUE);
276         }
277     }
278
279     if (This->wineD3DDevice->stencilBufferTarget) {
280         if (This->presentParms.Flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
281                 || ((IWineD3DSurfaceImpl *)This->wineD3DDevice->stencilBufferTarget)->Flags & SFLAG_DISCARD) {
282             surface_modify_ds_location(This->wineD3DDevice->stencilBufferTarget, SFLAG_DS_DISCARDED);
283         }
284     }
285
286     if(This->presentParms.PresentationInterval != WINED3DPRESENT_INTERVAL_IMMEDIATE && GL_SUPPORT(SGI_VIDEO_SYNC)) {
287         retval = GL_EXTCALL(glXGetVideoSyncSGI(&sync));
288         if(retval != 0) {
289             ERR("glXGetVideoSyncSGI failed(retval = %d\n", retval);
290         }
291
292         switch(This->presentParms.PresentationInterval) {
293             case WINED3DPRESENT_INTERVAL_DEFAULT:
294             case WINED3DPRESENT_INTERVAL_ONE:
295                 if(sync <= This->vSyncCounter) {
296                     retval = GL_EXTCALL(glXWaitVideoSyncSGI(1, 0, &This->vSyncCounter));
297                 } else {
298                     This->vSyncCounter = sync;
299                 }
300                 break;
301             case WINED3DPRESENT_INTERVAL_TWO:
302                 if(sync <= This->vSyncCounter + 1) {
303                     retval = GL_EXTCALL(glXWaitVideoSyncSGI(2, This->vSyncCounter & 0x1, &This->vSyncCounter));
304                 } else {
305                     This->vSyncCounter = sync;
306                 }
307                 break;
308             case WINED3DPRESENT_INTERVAL_THREE:
309                 if(sync <= This->vSyncCounter + 2) {
310                     retval = GL_EXTCALL(glXWaitVideoSyncSGI(3, This->vSyncCounter % 0x3, &This->vSyncCounter));
311                 } else {
312                     This->vSyncCounter = sync;
313                 }
314                 break;
315             case WINED3DPRESENT_INTERVAL_FOUR:
316                 if(sync <= This->vSyncCounter + 3) {
317                     retval = GL_EXTCALL(glXWaitVideoSyncSGI(4, This->vSyncCounter & 0x3, &This->vSyncCounter));
318                 } else {
319                     This->vSyncCounter = sync;
320                 }
321                 break;
322             default:
323                 FIXME("Unknown presentation interval %08x\n", This->presentParms.PresentationInterval);
324         }
325     }
326
327     TRACE("returning\n");
328     return WINED3D_OK;
329 }
330
331 static HRESULT WINAPI IWineD3DSwapChainImpl_SetDestWindowOverride(IWineD3DSwapChain *iface, HWND window) {
332     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
333     WINED3DLOCKED_RECT r;
334     BYTE *mem;
335
336     if(window == This->win_handle) return WINED3D_OK;
337
338     TRACE("Performing dest override of swapchain %p from window %p to %p\n", This, This->win_handle, window);
339     if(This->context[0] == This->wineD3DDevice->contexts[0]) {
340         /* The primary context 'owns' all the opengl resources. Destroying and recreating that context requires downloading
341          * all opengl resources, deleting the gl resources, destroying all other contexts, then recreating all other contexts
342          * and reload the resources
343          */
344         delete_opengl_contexts((IWineD3DDevice *) This->wineD3DDevice, iface);
345         This->win_handle             = window;
346         create_primary_opengl_context((IWineD3DDevice *) This->wineD3DDevice, iface);
347     } else {
348         This->win_handle             = window;
349
350         /* The old back buffer has to be copied over to the new back buffer. A lockrect - switchcontext - unlockrect
351          * would suffice in theory, but it is rather nasty and may cause troubles with future changes of the locking code
352          * So lock read only, copy the surface out, then lock with the discard flag and write back
353          */
354         IWineD3DSurface_LockRect(This->backBuffer[0], &r, NULL, WINED3DLOCK_READONLY);
355         mem = HeapAlloc(GetProcessHeap(), 0, r.Pitch * ((IWineD3DSurfaceImpl *) This->backBuffer[0])->currentDesc.Height);
356         memcpy(mem, r.pBits, r.Pitch * ((IWineD3DSurfaceImpl *) This->backBuffer[0])->currentDesc.Height);
357         IWineD3DSurface_UnlockRect(This->backBuffer[0]);
358
359         DestroyContext(This->wineD3DDevice, This->context[0]);
360         This->context[0] = CreateContext(This->wineD3DDevice, (IWineD3DSurfaceImpl *) This->frontBuffer, This->win_handle, FALSE /* pbuffer */, &This->presentParms);
361
362         IWineD3DSurface_LockRect(This->backBuffer[0], &r, NULL, WINED3DLOCK_DISCARD);
363         memcpy(r.pBits, mem, r.Pitch * ((IWineD3DSurfaceImpl *) This->backBuffer[0])->currentDesc.Height);
364         HeapFree(GetProcessHeap(), 0, mem);
365         IWineD3DSurface_UnlockRect(This->backBuffer[0]);
366     }
367     return WINED3D_OK;
368 }
369
370 const IWineD3DSwapChainVtbl IWineD3DSwapChain_Vtbl =
371 {
372     /* IUnknown */
373     IWineD3DBaseSwapChainImpl_QueryInterface,
374     IWineD3DBaseSwapChainImpl_AddRef,
375     IWineD3DBaseSwapChainImpl_Release,
376     /* IWineD3DSwapChain */
377     IWineD3DBaseSwapChainImpl_GetParent,
378     IWineD3DSwapChainImpl_Destroy,
379     IWineD3DBaseSwapChainImpl_GetDevice,
380     IWineD3DSwapChainImpl_Present,
381     IWineD3DSwapChainImpl_SetDestWindowOverride,
382     IWineD3DBaseSwapChainImpl_GetFrontBufferData,
383     IWineD3DBaseSwapChainImpl_GetBackBuffer,
384     IWineD3DBaseSwapChainImpl_GetRasterStatus,
385     IWineD3DBaseSwapChainImpl_GetDisplayMode,
386     IWineD3DBaseSwapChainImpl_GetPresentParameters,
387     IWineD3DBaseSwapChainImpl_SetGammaRamp,
388     IWineD3DBaseSwapChainImpl_GetGammaRamp
389 };
390
391 WineD3DContext *IWineD3DSwapChainImpl_CreateContextForThread(IWineD3DSwapChain *iface) {
392     WineD3DContext *ctx;
393     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *) iface;
394     WineD3DContext **newArray;
395
396     TRACE("Creating a new context for swapchain %p, thread %d\n", This, GetCurrentThreadId());
397
398     ctx = CreateContext(This->wineD3DDevice, (IWineD3DSurfaceImpl *) This->frontBuffer,
399                         This->context[0]->win_handle, FALSE /* pbuffer */, &This->presentParms);
400     if(!ctx) {
401         ERR("Failed to create a new context for the swapchain\n");
402         return NULL;
403     }
404
405     newArray = HeapAlloc(GetProcessHeap(), 0, sizeof(*newArray) * This->num_contexts + 1);
406     if(!newArray) {
407         ERR("Out of memory when trying to allocate a new context array\n");
408         DestroyContext(This->wineD3DDevice, ctx);
409         return NULL;
410     }
411     memcpy(newArray, This->context, sizeof(*newArray) * This->num_contexts);
412     HeapFree(GetProcessHeap(), 0, This->context);
413     newArray[This->num_contexts] = ctx;
414     This->context = newArray;
415     This->num_contexts++;
416
417     TRACE("Returning context %p\n", ctx);
418     return ctx;
419 }
420
421 void get_drawable_size_swapchain(IWineD3DSurfaceImpl *This, UINT *width, UINT *height) {
422     /* The drawable size of an onscreen drawable is the surface size.
423      * (Actually: The window size, but the surface is created in window size)
424      */
425     *width = This->currentDesc.Width;
426     *height = This->currentDesc.Height;
427 }