mcicda: Exclude unused headers.
[wine] / dlls / wined3d / surface.c
1 /*
2  * IWineD3DSurface Implementation
3  *
4  * Copyright 1998 Lionel Ulmer
5  * Copyright 2000-2001 TransGaming Technologies Inc.
6  * Copyright 2002-2005 Jason Edmeades
7  * Copyright 2002-2003 Raphael Junqueira
8  * Copyright 2004 Christian Costa
9  * Copyright 2005 Oliver Stieber
10  * Copyright 2006 Stefan Dösinger for CodeWeavers
11  * Copyright 2007 Henri Verbeet
12  *
13  * This library is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Lesser General Public
15  * License as published by the Free Software Foundation; either
16  * version 2.1 of the License, or (at your option) any later version.
17  *
18  * This library is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21  * Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public
24  * License along with this library; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26  */
27
28 #include "config.h"
29 #include "wine/port.h"
30 #include "wined3d_private.h"
31
32 WINE_DEFAULT_DEBUG_CHANNEL(d3d_surface);
33 #define GLINFO_LOCATION ((IWineD3DImpl *)(((IWineD3DDeviceImpl *)This->resource.wineD3DDevice)->wineD3D))->gl_info
34
35 typedef enum {
36     NO_CONVERSION,
37     CONVERT_PALETTED,
38     CONVERT_PALETTED_CK,
39     CONVERT_CK_565,
40     CONVERT_CK_5551,
41     CONVERT_CK_4444,
42     CONVERT_CK_4444_ARGB,
43     CONVERT_CK_1555,
44     CONVERT_555,
45     CONVERT_CK_RGB24,
46     CONVERT_CK_8888,
47     CONVERT_CK_8888_ARGB,
48     CONVERT_RGB32_888,
49     CONVERT_V8U8,
50     CONVERT_X8L8V8U8,
51     CONVERT_Q8W8V8U8,
52     CONVERT_V16U16
53 } CONVERT_TYPES;
54
55 HRESULT d3dfmt_convert_surface(BYTE *src, BYTE *dst, UINT pitch, UINT width, UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *surf);
56
57 static void surface_download_data(IWineD3DSurfaceImpl *This) {
58     if (This->resource.format == WINED3DFMT_DXT1 ||
59             This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
60             This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) {
61         if (!GL_SUPPORT(EXT_TEXTURE_COMPRESSION_S3TC)) { /* We can assume this as the texture would not have been created otherwise */
62             FIXME("(%p) : Attempting to lock a compressed texture when texture compression isn't supported by opengl\n", This);
63         } else {
64             TRACE("(%p) : Calling glGetCompressedTexImageARB level %d, format %#x, type %#x, data %p\n", This, This->glDescription.level,
65                 This->glDescription.glFormat, This->glDescription.glType, This->resource.allocatedMemory);
66
67             GL_EXTCALL(glGetCompressedTexImageARB(This->glDescription.target, This->glDescription.level, This->resource.allocatedMemory));
68             checkGLcall("glGetCompressedTexImageARB()");
69         }
70     } else {
71         void *mem;
72         int src_pitch = 0;
73         int dst_pitch = 0;
74
75          if(This->Flags & SFLAG_CONVERTED) {
76              FIXME("Read back converted textures unsupported\n");
77              return;
78          }
79
80         if (This->Flags & SFLAG_NONPOW2) {
81             src_pitch = This->bytesPerPixel * This->pow2Width;
82             dst_pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);
83             src_pitch = (src_pitch + SURFACE_ALIGNMENT - 1) & ~(SURFACE_ALIGNMENT - 1);
84             mem = HeapAlloc(GetProcessHeap(), 0, src_pitch * This->pow2Height);
85         } else {
86             mem = This->resource.allocatedMemory;
87         }
88
89         TRACE("(%p) : Calling glGetTexImage level %d, format %#x, type %#x, data %p\n", This, This->glDescription.level,
90                 This->glDescription.glFormat, This->glDescription.glType, mem);
91
92         glGetTexImage(This->glDescription.target, This->glDescription.level, This->glDescription.glFormat,
93                 This->glDescription.glType, mem);
94         checkGLcall("glGetTexImage()");
95
96         if (This->Flags & SFLAG_NONPOW2) {
97             LPBYTE src_data, dst_data;
98             int y;
99             /*
100              * Some games (e.g. warhammer 40k) don't work properly with the odd pitches, preventing
101              * the surface pitch from being used to box non-power2 textures. Instead we have to use a hack to
102              * repack the texture so that the bpp * width pitch can be used instead of bpp * pow2width.
103              *
104              * We're doing this...
105              *
106              * instead of boxing the texture :
107              * |<-texture width ->|  -->pow2width|   /\
108              * |111111111111111111|              |   |
109              * |222 Texture 222222| boxed empty  | texture height
110              * |3333 Data 33333333|              |   |
111              * |444444444444444444|              |   \/
112              * -----------------------------------   |
113              * |     boxed  empty | boxed empty  | pow2height
114              * |                  |              |   \/
115              * -----------------------------------
116              *
117              *
118              * we're repacking the data to the expected texture width
119              *
120              * |<-texture width ->|  -->pow2width|   /\
121              * |111111111111111111222222222222222|   |
122              * |222333333333333333333444444444444| texture height
123              * |444444                           |   |
124              * |                                 |   \/
125              * |                                 |   |
126              * |            empty                | pow2height
127              * |                                 |   \/
128              * -----------------------------------
129              *
130              * == is the same as
131              *
132              * |<-texture width ->|    /\
133              * |111111111111111111|
134              * |222222222222222222|texture height
135              * |333333333333333333|
136              * |444444444444444444|    \/
137              * --------------------
138              *
139              * this also means that any references to allocatedMemory should work with the data as if were a
140              * standard texture with a non-power2 width instead of texture boxed up to be a power2 texture.
141              *
142              * internally the texture is still stored in a boxed format so any references to textureName will
143              * get a boxed texture with width pow2width and not a texture of width currentDesc.Width.
144              *
145              * Performance should not be an issue, because applications normally do not lock the surfaces when
146              * rendering. If an app does, the SFLAG_DYNLOCK flag will kick in and the memory copy won't be released,
147              * and doesn't have to be re-read.
148              */
149             src_data = mem;
150             dst_data = This->resource.allocatedMemory;
151             TRACE("(%p) : Repacking the surface data from pitch %d to pitch %d\n", This, src_pitch, dst_pitch);
152             for (y = 1 ; y < This->currentDesc.Height; y++) {
153                 /* skip the first row */
154                 src_data += src_pitch;
155                 dst_data += dst_pitch;
156                 memcpy(dst_data, src_data, dst_pitch);
157             }
158
159             HeapFree(GetProcessHeap(), 0, mem);
160         }
161     }
162 }
163
164 static void surface_upload_data(IWineD3DSurfaceImpl *This, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *data) {
165     if (This->resource.format == WINED3DFMT_DXT1 ||
166             This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
167             This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) {
168         if (!GL_SUPPORT(EXT_TEXTURE_COMPRESSION_S3TC)) {
169             FIXME("Using DXT1/3/5 without advertized support\n");
170         } else {
171             if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
172                 /* Neither NONPOW2, DIBSECTION nor OVERSIZE flags can be set on compressed textures */
173                 This->Flags |= SFLAG_CLIENT;
174             }
175
176             TRACE("(%p) : Calling glCompressedTexSubImage2D w %d, h %d, data %p\n", This, width, height, data);
177             ENTER_GL();
178             /* glCompressedTexSubImage2D for uploading and glTexImage2D for allocating does not work well on some drivers(r200 dri, MacOS ATI driver)
179              * glCompressedTexImage2D does not accept NULL pointers. So for compressed textures surface_allocate_surface does nothing, and this
180              * function uses glCompressedTexImage2D instead of the SubImage call
181              */
182             GL_EXTCALL(glCompressedTexImage2DARB(This->glDescription.target, This->glDescription.level, This->glDescription.glFormatInternal,
183                        width, height, 0 /* border */, This->resource.size, data));
184             checkGLcall("glCompressedTexSubImage2D");
185             LEAVE_GL();
186         }
187     } else {
188         TRACE("(%p) : Calling glTexSubImage2D w %d,  h %d, data, %p\n", This, width, height, data);
189         ENTER_GL();
190         glTexSubImage2D(This->glDescription.target, This->glDescription.level, 0, 0, width, height, format, type, data);
191         checkGLcall("glTexSubImage2D");
192         LEAVE_GL();
193     }
194 }
195
196 static void surface_allocate_surface(IWineD3DSurfaceImpl *This, GLenum internal, GLsizei width, GLsizei height, GLenum format, GLenum type) {
197     BOOL enable_client_storage = FALSE;
198
199     TRACE("(%p) : Creating surface (target %#x)  level %d, d3d format %s, internal format %#x, width %d, height %d, gl format %#x, gl type=%#x\n", This,
200             This->glDescription.target, This->glDescription.level, debug_d3dformat(This->resource.format), internal, width, height, format, type);
201
202     if (This->resource.format == WINED3DFMT_DXT1 ||
203             This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
204             This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) {
205         /* glCompressedTexImage2D does not accept NULL pointers, so we cannot allocate a compressed texture without uploading data */
206         TRACE("Not allocating compressed surfaces, surface_upload_data will specify them\n");
207         return;
208     }
209
210     ENTER_GL();
211
212     if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
213         if(This->Flags & (SFLAG_NONPOW2 | SFLAG_DIBSECTION | SFLAG_OVERSIZE | SFLAG_CONVERTED) || This->resource.allocatedMemory == NULL) {
214             /* In some cases we want to disable client storage.
215              * SFLAG_NONPOW2 has a bigger opengl texture than the client memory, and different pitches
216              * SFLAG_DIBSECTION: Dibsections may have read / write protections on the memory. Avoid issues...
217              * SFLAG_OVERSIZE: The gl texture is smaller than the allocated memory
218              * SFLAG_CONVERTED: The conversion destination memory is freed after loading the surface
219              * allocatedMemory == NULL: Not defined in the extension. Seems to disable client storage effectively
220              */
221             glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
222             checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
223             This->Flags &= SFLAG_CLIENT;
224             enable_client_storage = TRUE;
225         } else {
226             This->Flags |= SFLAG_CLIENT;
227             /* Below point opengl to our allocated texture memory */
228         }
229     }
230     glTexImage2D(This->glDescription.target, This->glDescription.level, internal, width, height, 0, format, type,
231                  This->Flags & SFLAG_CLIENT ? This->resource.allocatedMemory : NULL);
232     checkGLcall("glTexImage2D");
233
234     if(enable_client_storage) {
235         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
236         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
237     }
238     LEAVE_GL();
239
240     This->Flags |= SFLAG_ALLOCATED;
241 }
242
243 /* In D3D the depth stencil dimensions have to be greater than or equal to the
244  * render target dimensions. With FBOs, the dimensions have to be an exact match. */
245 /* TODO: We should synchronize the renderbuffer's content with the texture's content. */
246 void surface_set_compatible_renderbuffer(IWineD3DSurface *iface, unsigned int width, unsigned int height) {
247     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
248     renderbuffer_entry_t *entry;
249     GLuint renderbuffer = 0;
250     unsigned int src_width, src_height;
251
252     src_width = This->pow2Width;
253     src_height = This->pow2Height;
254
255     /* A depth stencil smaller than the render target is not valid */
256     if (width > src_width || height > src_height) return;
257
258     /* Remove any renderbuffer set if the sizes match */
259     if (width == src_width && height == src_height) {
260         This->current_renderbuffer = NULL;
261         return;
262     }
263
264     /* Look if we've already got a renderbuffer of the correct dimensions */
265     LIST_FOR_EACH_ENTRY(entry, &This->renderbuffers, renderbuffer_entry_t, entry) {
266         if (entry->width == width && entry->height == height) {
267             renderbuffer = entry->id;
268             This->current_renderbuffer = entry;
269             break;
270         }
271     }
272
273     if (!renderbuffer) {
274         const PixelFormatDesc *format_entry = getFormatDescEntry(This->resource.format);
275
276         GL_EXTCALL(glGenRenderbuffersEXT(1, &renderbuffer));
277         GL_EXTCALL(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, renderbuffer));
278         GL_EXTCALL(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, format_entry->glFormat, width, height));
279
280         entry = HeapAlloc(GetProcessHeap(), 0, sizeof(renderbuffer_entry_t));
281         entry->width = width;
282         entry->height = height;
283         entry->id = renderbuffer;
284         list_add_head(&This->renderbuffers, &entry->entry);
285
286         This->current_renderbuffer = entry;
287     }
288
289     checkGLcall("set_compatible_renderbuffer");
290 }
291
292 GLenum surface_get_gl_buffer(IWineD3DSurface *iface, IWineD3DSwapChain *swapchain) {
293     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
294     IWineD3DSwapChainImpl *swapchain_impl = (IWineD3DSwapChainImpl *)swapchain;
295
296     TRACE("(%p) : swapchain %p\n", This, swapchain);
297
298     if (swapchain_impl->backBuffer && swapchain_impl->backBuffer[0] == iface) {
299         TRACE("Returning GL_BACK\n");
300         return GL_BACK;
301     } else if (swapchain_impl->frontBuffer == iface) {
302         TRACE("Returning GL_FRONT\n");
303         return GL_FRONT;
304     }
305
306     FIXME("Higher back buffer, returning GL_BACK\n");
307     return GL_BACK;
308 }
309
310 /* *******************************************
311    IWineD3DSurface IUnknown parts follow
312    ******************************************* */
313 HRESULT WINAPI IWineD3DSurfaceImpl_QueryInterface(IWineD3DSurface *iface, REFIID riid, LPVOID *ppobj)
314 {
315     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
316     /* Warn ,but be nice about things */
317     TRACE("(%p)->(%s,%p)\n", This,debugstr_guid(riid),ppobj);
318
319     if (IsEqualGUID(riid, &IID_IUnknown)
320         || IsEqualGUID(riid, &IID_IWineD3DBase)
321         || IsEqualGUID(riid, &IID_IWineD3DResource)
322         || IsEqualGUID(riid, &IID_IWineD3DSurface)) {
323         IUnknown_AddRef((IUnknown*)iface);
324         *ppobj = This;
325         return S_OK;
326     }
327     *ppobj = NULL;
328     return E_NOINTERFACE;
329 }
330
331 ULONG WINAPI IWineD3DSurfaceImpl_AddRef(IWineD3DSurface *iface) {
332     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
333     ULONG ref = InterlockedIncrement(&This->resource.ref);
334     TRACE("(%p) : AddRef increasing from %d\n", This,ref - 1);
335     return ref;
336 }
337
338 ULONG WINAPI IWineD3DSurfaceImpl_Release(IWineD3DSurface *iface) {
339     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
340     ULONG ref = InterlockedDecrement(&This->resource.ref);
341     TRACE("(%p) : Releasing from %d\n", This, ref + 1);
342     if (ref == 0) {
343         IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->resource.wineD3DDevice;
344         renderbuffer_entry_t *entry, *entry2;
345         TRACE("(%p) : cleaning up\n", This);
346
347         if(iface == device->lastActiveRenderTarget) {
348             IWineD3DSwapChainImpl *swapchain = device->swapchains ? (IWineD3DSwapChainImpl *) device->swapchains[0] : NULL;
349
350             TRACE("Last active render target destroyed\n");
351             /* Find a replacement surface for the currently active back buffer. The context manager does not do NULL
352              * checks, so switch to a valid target as long as the currently set surface is still valid. Use the
353              * surface of the implicit swpchain. If that is the same as the destroyed surface the device is destroyed
354              * and the lastActiveRenderTarget member shouldn't matter
355              */
356             if(swapchain) {
357                 ENTER_GL(); /* For ActivateContext */
358                 if(swapchain->backBuffer && swapchain->backBuffer[0] != iface) {
359                     TRACE("Activating primary back buffer\n");
360                     ActivateContext(device, swapchain->backBuffer[0], CTXUSAGE_RESOURCELOAD);
361                 } else if(!swapchain->backBuffer && swapchain->frontBuffer != iface) {
362                     /* Single buffering environment */
363                     TRACE("Activating primary front buffer\n");
364                     ActivateContext(device, swapchain->frontBuffer, CTXUSAGE_RESOURCELOAD);
365                 } else {
366                     TRACE("Device is being destroyed, setting lastActiveRenderTarget = 0xdeadbabe\n");
367                     /* Implicit render target destroyed, that means the device is being destroyed
368                      * whatever we set here, it shouldn't matter
369                      */
370                     device->lastActiveRenderTarget = (IWineD3DSurface *) 0xdeadbabe;
371                 }
372                 LEAVE_GL();
373             } else {
374                 /* May happen during ddraw uninitialization */
375                 TRACE("Render target set, but swapchain does not exist!\n");
376                 device->lastActiveRenderTarget = (IWineD3DSurface *) 0xdeadcafe;
377             }
378         }
379
380         if (This->glDescription.textureName != 0) { /* release the openGL texture.. */
381             ENTER_GL();
382
383             /* Need a context to destroy the texture. Use the currently active render target, but only if
384              * the primary render target exists. Otherwise lastActiveRenderTarget is garbage, see above.
385              * When destroying the primary rt, Uninit3D will activate a context before doing anything
386              */
387             if(device->render_targets[0]) {
388                 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
389             }
390
391             TRACE("Deleting texture %d\n", This->glDescription.textureName);
392             glDeleteTextures(1, &This->glDescription.textureName);
393             LEAVE_GL();
394         }
395
396         if(This->Flags & SFLAG_DIBSECTION) {
397             /* Release the DC */
398             SelectObject(This->hDC, This->dib.holdbitmap);
399             DeleteDC(This->hDC);
400             /* Release the DIB section */
401             DeleteObject(This->dib.DIBsection);
402             This->dib.bitmap_data = NULL;
403             This->resource.allocatedMemory = NULL;
404         }
405         if(This->Flags & SFLAG_USERPTR) IWineD3DSurface_SetMem(iface, NULL);
406
407         HeapFree(GetProcessHeap(), 0, This->palette9);
408
409         IWineD3DResourceImpl_CleanUp((IWineD3DResource *)iface);
410         if(iface == device->ddraw_primary)
411             device->ddraw_primary = NULL;
412
413         LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
414             GL_EXTCALL(glDeleteRenderbuffersEXT(1, &entry->id));
415             HeapFree(GetProcessHeap(), 0, entry);
416         }
417
418         TRACE("(%p) Released\n", This);
419         HeapFree(GetProcessHeap(), 0, This);
420
421     }
422     return ref;
423 }
424
425 /* ****************************************************
426    IWineD3DSurface IWineD3DResource parts follow
427    **************************************************** */
428 HRESULT WINAPI IWineD3DSurfaceImpl_GetDevice(IWineD3DSurface *iface, IWineD3DDevice** ppDevice) {
429     return IWineD3DResourceImpl_GetDevice((IWineD3DResource *)iface, ppDevice);
430 }
431
432 HRESULT WINAPI IWineD3DSurfaceImpl_SetPrivateData(IWineD3DSurface *iface, REFGUID refguid, CONST void* pData, DWORD SizeOfData, DWORD Flags) {
433     return IWineD3DResourceImpl_SetPrivateData((IWineD3DResource *)iface, refguid, pData, SizeOfData, Flags);
434 }
435
436 HRESULT WINAPI IWineD3DSurfaceImpl_GetPrivateData(IWineD3DSurface *iface, REFGUID refguid, void* pData, DWORD* pSizeOfData) {
437     return IWineD3DResourceImpl_GetPrivateData((IWineD3DResource *)iface, refguid, pData, pSizeOfData);
438 }
439
440 HRESULT WINAPI IWineD3DSurfaceImpl_FreePrivateData(IWineD3DSurface *iface, REFGUID refguid) {
441     return IWineD3DResourceImpl_FreePrivateData((IWineD3DResource *)iface, refguid);
442 }
443
444 DWORD   WINAPI IWineD3DSurfaceImpl_SetPriority(IWineD3DSurface *iface, DWORD PriorityNew) {
445     return IWineD3DResourceImpl_SetPriority((IWineD3DResource *)iface, PriorityNew);
446 }
447
448 DWORD   WINAPI IWineD3DSurfaceImpl_GetPriority(IWineD3DSurface *iface) {
449     return IWineD3DResourceImpl_GetPriority((IWineD3DResource *)iface);
450 }
451
452 void WINAPI IWineD3DSurfaceImpl_PreLoad(IWineD3DSurface *iface) {
453     /* TODO: check for locks */
454     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
455     IWineD3DBaseTexture *baseTexture = NULL;
456     IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
457
458     TRACE("(%p)Checking to see if the container is a base texture\n", This);
459     if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
460         TRACE("Passing to conatiner\n");
461         IWineD3DBaseTexture_PreLoad(baseTexture);
462         IWineD3DBaseTexture_Release(baseTexture);
463     } else {
464     TRACE("(%p) : About to load surface\n", This);
465
466     ENTER_GL();
467     if(!device->isInDraw) {
468         ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
469     }
470
471     glEnable(This->glDescription.target);/* make sure texture support is enabled in this context */
472     if (!This->glDescription.level) {
473         if (!This->glDescription.textureName) {
474             glGenTextures(1, &This->glDescription.textureName);
475             checkGLcall("glGenTextures");
476             TRACE("Surface %p given name %d\n", This, This->glDescription.textureName);
477         }
478         glBindTexture(This->glDescription.target, This->glDescription.textureName);
479         checkGLcall("glBindTexture");
480         IWineD3DSurface_LoadTexture(iface);
481         /* This is where we should be reducing the amount of GLMemoryUsed */
482     } else if (This->glDescription.textureName) { /* NOTE: the level 0 surface of a mpmapped texture must be loaded first! */
483         /* assume this is a coding error not a real error for now */
484         FIXME("Mipmap surface has a glTexture bound to it!\n");
485     }
486     if (This->resource.pool == WINED3DPOOL_DEFAULT) {
487        /* Tell opengl to try and keep this texture in video ram (well mostly) */
488        GLclampf tmp;
489        tmp = 0.9f;
490         glPrioritizeTextures(1, &This->glDescription.textureName, &tmp);
491     }
492     LEAVE_GL();
493     }
494     return;
495 }
496
497 WINED3DRESOURCETYPE WINAPI IWineD3DSurfaceImpl_GetType(IWineD3DSurface *iface) {
498     TRACE("(%p) : calling resourceimpl_GetType\n", iface);
499     return IWineD3DResourceImpl_GetType((IWineD3DResource *)iface);
500 }
501
502 HRESULT WINAPI IWineD3DSurfaceImpl_GetParent(IWineD3DSurface *iface, IUnknown **pParent) {
503     TRACE("(%p) : calling resourceimpl_GetParent\n", iface);
504     return IWineD3DResourceImpl_GetParent((IWineD3DResource *)iface, pParent);
505 }
506
507 /* ******************************************************
508    IWineD3DSurface IWineD3DSurface parts follow
509    ****************************************************** */
510
511 HRESULT WINAPI IWineD3DSurfaceImpl_GetContainer(IWineD3DSurface* iface, REFIID riid, void** ppContainer) {
512     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
513     IWineD3DBase *container = 0;
514
515     TRACE("(This %p, riid %s, ppContainer %p)\n", This, debugstr_guid(riid), ppContainer);
516
517     if (!ppContainer) {
518         ERR("Called without a valid ppContainer.\n");
519     }
520
521     /** From MSDN:
522      * If the surface is created using CreateImageSurface/CreateOffscreenPlainSurface, CreateRenderTarget,
523      * or CreateDepthStencilSurface, the surface is considered stand alone. In this case,
524      * GetContainer will return the Direct3D device used to create the surface.
525      */
526     if (This->container) {
527         container = This->container;
528     } else {
529         container = (IWineD3DBase *)This->resource.wineD3DDevice;
530     }
531
532     TRACE("Relaying to QueryInterface\n");
533     return IUnknown_QueryInterface(container, riid, ppContainer);
534 }
535
536 HRESULT WINAPI IWineD3DSurfaceImpl_GetDesc(IWineD3DSurface *iface, WINED3DSURFACE_DESC *pDesc) {
537     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
538
539     TRACE("(%p) : copying into %p\n", This, pDesc);
540     if(pDesc->Format != NULL)             *(pDesc->Format) = This->resource.format;
541     if(pDesc->Type != NULL)               *(pDesc->Type)   = This->resource.resourceType;
542     if(pDesc->Usage != NULL)              *(pDesc->Usage)              = This->resource.usage;
543     if(pDesc->Pool != NULL)               *(pDesc->Pool)               = This->resource.pool;
544     if(pDesc->Size != NULL)               *(pDesc->Size)               = This->resource.size;   /* dx8 only */
545     if(pDesc->MultiSampleType != NULL)    *(pDesc->MultiSampleType)    = This->currentDesc.MultiSampleType;
546     if(pDesc->MultiSampleQuality != NULL) *(pDesc->MultiSampleQuality) = This->currentDesc.MultiSampleQuality;
547     if(pDesc->Width != NULL)              *(pDesc->Width)              = This->currentDesc.Width;
548     if(pDesc->Height != NULL)             *(pDesc->Height)             = This->currentDesc.Height;
549     return WINED3D_OK;
550 }
551
552 void WINAPI IWineD3DSurfaceImpl_SetGlTextureDesc(IWineD3DSurface *iface, UINT textureName, int target) {
553     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
554     TRACE("(%p) : setting textureName %u, target %i\n", This, textureName, target);
555     if (This->glDescription.textureName == 0 && textureName != 0) {
556         This->Flags &= ~SFLAG_INTEXTURE;
557         IWineD3DSurface_AddDirtyRect(iface, NULL);
558     }
559     This->glDescription.textureName = textureName;
560     This->glDescription.target      = target;
561     This->Flags &= ~SFLAG_ALLOCATED;
562 }
563
564 void WINAPI IWineD3DSurfaceImpl_GetGlDesc(IWineD3DSurface *iface, glDescriptor **glDescription) {
565     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
566     TRACE("(%p) : returning %p\n", This, &This->glDescription);
567     *glDescription = &This->glDescription;
568 }
569
570 /* TODO: think about moving this down to resource? */
571 const void *WINAPI IWineD3DSurfaceImpl_GetData(IWineD3DSurface *iface) {
572     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
573     /* This should only be called for sysmem textures, it may be a good idea to extend this to all pools at some point in the futture  */
574     if (This->resource.pool != WINED3DPOOL_SYSTEMMEM) {
575         FIXME(" (%p)Attempting to get system memory for a non-system memory texture\n", iface);
576     }
577     return (CONST void*)(This->resource.allocatedMemory);
578 }
579
580 static void read_from_framebuffer(IWineD3DSurfaceImpl *This, CONST RECT *rect, void *dest, UINT pitch, BOOL srcUpsideDown) {
581     BYTE *mem;
582     GLint fmt;
583     GLint type;
584     BYTE *row, *top, *bottom;
585     int i;
586     BOOL bpp;
587
588     switch(This->resource.format)
589     {
590         case WINED3DFMT_P8:
591         {
592             /* GL can't return palettized data, so read ARGB pixels into a
593              * separate block of memory and convert them into palettized format
594              * in software. Slow, but if the app means to use palettized render
595              * targets and locks it...
596              *
597              * Use GL_RGB, GL_UNSIGNED_BYTE to read the surface for performance reasons
598              * Don't use GL_BGR as in the WINED3DFMT_R8G8B8 case, instead watch out
599              * for the color channels when palettizing the colors.
600              */
601             fmt = GL_RGB;
602             type = GL_UNSIGNED_BYTE;
603             pitch *= 3;
604             mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * 3);
605             if(!mem) {
606                 ERR("Out of memory\n");
607                 return;
608             }
609             bpp = This->bytesPerPixel * 3;
610         }
611         break;
612
613         default:
614             mem = dest;
615             fmt = This->glDescription.glFormat;
616             type = This->glDescription.glType;
617             bpp = This->bytesPerPixel;
618     }
619
620     glReadPixels(rect->left, rect->top,
621                  rect->right - rect->left,
622                  rect->bottom - rect->top,
623                  fmt, type, mem);
624     vcheckGLcall("glReadPixels");
625
626     /* TODO: Merge this with the palettization loop below for P8 targets */
627
628     if(!srcUpsideDown) {
629         UINT len, off;
630         /* glReadPixels returns the image upside down, and there is no way to prevent this.
631             Flip the lines in software */
632         len = (rect->right - rect->left) * bpp;
633         off = rect->left * bpp;
634
635         row = HeapAlloc(GetProcessHeap(), 0, len);
636         if(!row) {
637             ERR("Out of memory\n");
638             if(This->resource.format == WINED3DFMT_P8) HeapFree(GetProcessHeap(), 0, mem);
639             return;
640         }
641
642         top = mem + pitch * rect->top;
643         bottom = ((BYTE *) mem) + pitch * ( rect->bottom - rect->top - 1);
644         for(i = 0; i < (rect->bottom - rect->top) / 2; i++) {
645             memcpy(row, top + off, len);
646             memcpy(top + off, bottom + off, len);
647             memcpy(bottom + off, row, len);
648             top += pitch;
649             bottom -= pitch;
650         }
651         HeapFree(GetProcessHeap(), 0, row);
652     }
653
654     if(This->resource.format == WINED3DFMT_P8) {
655         PALETTEENTRY *pal;
656         DWORD width = pitch / 3;
657         int x, y, c;
658         if(This->palette) {
659             pal = This->palette->palents;
660         } else {
661             pal = This->resource.wineD3DDevice->palettes[This->resource.wineD3DDevice->currentPalette];
662         }
663
664         for(y = rect->top; y < rect->bottom; y++) {
665             for(x = rect->left; x < rect->right; x++) {
666                 /*                      start              lines            pixels      */
667                 BYTE *blue =  (BYTE *) ((BYTE *) mem) + y * pitch + x * (sizeof(BYTE) * 3);
668                 BYTE *green = blue  + 1;
669                 BYTE *red =   green + 1;
670
671                 for(c = 0; c < 256; c++) {
672                     if(*red   == pal[c].peRed   &&
673                        *green == pal[c].peGreen &&
674                        *blue  == pal[c].peBlue)
675                     {
676                         *((BYTE *) dest + y * width + x) = c;
677                         break;
678                     }
679                 }
680             }
681         }
682         HeapFree(GetProcessHeap(), 0, mem);
683     }
684 }
685
686 static HRESULT WINAPI IWineD3DSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags) {
687     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
688     IWineD3DDeviceImpl  *myDevice = This->resource.wineD3DDevice;
689     IWineD3DSwapChainImpl *swapchain = NULL;
690
691     TRACE("(%p) : rect@%p flags(%08x), output lockedRect@%p, memory@%p\n", This, pRect, Flags, pLockedRect, This->resource.allocatedMemory);
692
693     if (!(This->Flags & SFLAG_LOCKABLE)) {
694         /* Note: UpdateTextures calls CopyRects which calls this routine to populate the
695               texture regions, and since the destination is an unlockable region we need
696               to tolerate this                                                           */
697         TRACE("Warning: trying to lock unlockable surf@%p\n", This);
698         /*return WINED3DERR_INVALIDCALL; */
699     }
700
701     pLockedRect->Pitch = IWineD3DSurface_GetPitch(iface);
702
703     /* Mark the surface locked */
704     This->Flags |= SFLAG_LOCKED;
705
706     /* Whatever surface we have, make sure that there is memory allocated for the downloaded copy */
707     if(!This->resource.allocatedMemory) {
708         This->resource.allocatedMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + 4);
709         This->Flags &= ~SFLAG_INSYSMEM; /* This is the marker that surface data has to be downloaded */
710     }
711
712     /* Calculate the correct start address to report */
713     if (NULL == pRect) {
714         pLockedRect->pBits = This->resource.allocatedMemory;
715         This->lockedRect.left   = 0;
716         This->lockedRect.top    = 0;
717         This->lockedRect.right  = This->currentDesc.Width;
718         This->lockedRect.bottom = This->currentDesc.Height;
719         TRACE("Locked Rect (%p) = l %d, t %d, r %d, b %d\n", &This->lockedRect, This->lockedRect.left, This->lockedRect.top, This->lockedRect.right, This->lockedRect.bottom);
720     } else {
721         TRACE("Lock Rect (%p) = l %d, t %d, r %d, b %d\n", pRect, pRect->left, pRect->top, pRect->right, pRect->bottom);
722
723         /* DXTn textures are based on compressed blocks of 4x4 pixels, each
724          * 16 bytes large (8 bytes in case of DXT1). Because of that Pitch has
725          * slightly different meaning compared to regular textures. For DXTn
726          * textures Pitch is the size of a row of blocks, 4 high and "width"
727          * long. The x offset is calculated differently as well, since moving 4
728          * pixels to the right actually moves an entire 4x4 block to right, ie
729          * 16 bytes (8 in case of DXT1). */
730         if (This->resource.format == WINED3DFMT_DXT1) {
731             pLockedRect->pBits = This->resource.allocatedMemory + (pLockedRect->Pitch * pRect->top / 4) + (pRect->left * 2);
732         } else if (This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3
733                 || This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) {
734             pLockedRect->pBits = This->resource.allocatedMemory + (pLockedRect->Pitch * pRect->top / 4) + (pRect->left * 4);
735         } else {
736             pLockedRect->pBits = This->resource.allocatedMemory + (pLockedRect->Pitch * pRect->top) + (pRect->left * This->bytesPerPixel);
737         }
738         This->lockedRect.left   = pRect->left;
739         This->lockedRect.top    = pRect->top;
740         This->lockedRect.right  = pRect->right;
741         This->lockedRect.bottom = pRect->bottom;
742     }
743
744     if (This->Flags & SFLAG_NONPOW2) {
745         TRACE("Locking non-power 2 texture\n");
746     }
747
748     /* Performance optimization: Count how often a surface is locked, if it is locked regularly do not throw away the system memory copy.
749      * This avoids the need to download the surface from opengl all the time. The surface is still downloaded if the opengl texture is
750      * changed
751      */
752     if(!(This->Flags & SFLAG_DYNLOCK)) {
753         This->lockCount++;
754         /* MAXLOCKCOUNT is defined in wined3d_private.h */
755         if(This->lockCount > MAXLOCKCOUNT) {
756             TRACE("Surface is locked regularily, not freeing the system memory copy any more\n");
757             This->Flags |= SFLAG_DYNLOCK;
758         }
759     }
760
761     if((Flags & WINED3DLOCK_DISCARD) || (This->Flags & SFLAG_INSYSMEM)) {
762         TRACE("WINED3DLOCK_DISCARD flag passed, or local copy is up to date, not downloading data\n");
763         goto lock_end;
764     }
765
766     /* Now download the surface content from opengl
767      * Use the render target readback if the surface is on a swapchain(=onscreen render target) or the current primary target
768      * Offscreen targets which are not active at the moment or are higher targets(fbos) can be locked with the texture path
769      */
770     IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain);
771     if(swapchain || iface == myDevice->render_targets[0]) {
772         BOOL srcIsUpsideDown;
773
774         if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
775             static BOOL warned = FALSE;
776             if(!warned) {
777                 ERR("The application tries to lock the render target, but render target locking is disabled\n");
778                 warned = TRUE;
779             }
780             if(swapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
781             return WINED3D_OK;
782         }
783
784         /* Activate the surface. Set it up for blitting now, although not necessarily needed for LockRect.
785          * Certain graphics drivers seem to dislike some enabled states when reading from opengl, the blitting usage
786          * should help here. Furthermore unlockrect will need the context set up for blitting. The context manager will find
787          * context->last_was_blit set on the unlock.
788          */
789         ENTER_GL();
790         ActivateContext(myDevice, iface, CTXUSAGE_BLIT);
791
792         /* Select the correct read buffer, and give some debug output.
793          * There is no need to keep track of the current read buffer or reset it, every part of the code
794          * that reads sets the read buffer as desired.
795          */
796         if(!swapchain) {
797             /* Locking the primary render target which is not on a swapchain(=offscreen render target).
798              * Read from the back buffer
799              */
800             TRACE("Locking offscreen render target\n");
801             glReadBuffer(myDevice->offscreenBuffer);
802             srcIsUpsideDown = TRUE;
803         } else {
804             GLenum buffer = surface_get_gl_buffer(iface, (IWineD3DSwapChain *)swapchain);
805             TRACE("Locking %#x buffer\n", buffer);
806             glReadBuffer(buffer);
807             checkGLcall("glReadBuffer");
808
809             IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
810             srcIsUpsideDown = FALSE;
811         }
812
813         switch(wined3d_settings.rendertargetlock_mode) {
814             case RTL_AUTO:
815             case RTL_READDRAW:
816             case RTL_READTEX:
817                 read_from_framebuffer(This, &This->lockedRect, This->resource.allocatedMemory, pLockedRect->Pitch, srcIsUpsideDown);
818                 break;
819
820             case RTL_TEXDRAW:
821             case RTL_TEXTEX:
822                 read_from_framebuffer(This, &This->lockedRect, This->resource.allocatedMemory, pLockedRect->Pitch, srcIsUpsideDown);
823                 FIXME("Reading from render target with a texture isn't implemented yet, falling back to framebuffer reading\n");
824                 break;
825         }
826         LEAVE_GL();
827
828         /* Mark the local copy up to date if a full download was done */
829         if(This->lockedRect.left == 0 &&
830            This->lockedRect.top == 0 &&
831            This->lockedRect.right == This->currentDesc.Width &&
832            This->lockedRect.bottom == This->currentDesc.Height) {
833             This->Flags |= SFLAG_INSYSMEM;
834         }
835     } else if(iface == myDevice->stencilBufferTarget) {
836         /** the depth stencil in openGL has a format of GL_FLOAT
837          * which should be good for WINED3DFMT_D16_LOCKABLE
838          * and WINED3DFMT_D16
839          * it is unclear what format the stencil buffer is in except.
840          * 'Each index is converted to fixed point...
841          * If GL_MAP_STENCIL is GL_TRUE, indices are replaced by their
842          * mappings in the table GL_PIXEL_MAP_S_TO_S.
843          * glReadPixels(This->lockedRect.left,
844          *             This->lockedRect.bottom - j - 1,
845          *             This->lockedRect.right - This->lockedRect.left,
846          *             1,
847          *             GL_DEPTH_COMPONENT,
848          *             type,
849          *             (char *)pLockedRect->pBits + (pLockedRect->Pitch * (j-This->lockedRect.top)));
850          *
851          * Depth Stencil surfaces which are not the current depth stencil target should have their data in a
852          * gl texture(next path), or in local memory(early return because of set SFLAG_INSYSMEM above). If
853          * none of that is the case the problem is not in this function :-)
854          ********************************************/
855         FIXME("Depth stencil locking not supported yet\n");
856     } else {
857         /* This path is for normal surfaces, offscreen render targets and everything else that is in a gl texture */
858         TRACE("locking an ordinarary surface\n");
859
860         if (0 != This->glDescription.textureName) {
861             /* Now I have to copy thing bits back */
862
863             ENTER_GL();
864
865             if(myDevice->createParms.BehaviorFlags & WINED3DCREATE_MULTITHREADED) {
866                 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
867             }
868
869             /* Make sure that a proper texture unit is selected, bind the texture and dirtify the sampler to restore the texture on the next draw */
870             if (GL_SUPPORT(ARB_MULTITEXTURE)) {
871                 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
872                 checkGLcall("glActiveTextureARB");
873             }
874             IWineD3DDeviceImpl_MarkStateDirty(This->resource.wineD3DDevice, STATE_SAMPLER(0));
875             IWineD3DSurface_PreLoad(iface);
876
877             surface_download_data(This);
878             LEAVE_GL();
879         }
880
881         /* The local copy is now up to date to the opengl one because a full download was done */
882         This->Flags |= SFLAG_INSYSMEM;
883     }
884
885 lock_end:
886     if (Flags & (WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY)) {
887         /* Don't dirtify */
888     } else {
889         IWineD3DBaseTexture *pBaseTexture;
890         /**
891          * Dirtify on lock
892          * as seen in msdn docs
893          */
894         IWineD3DSurface_AddDirtyRect(iface, &This->lockedRect);
895
896         /** Dirtify Container if needed */
897         if (WINED3D_OK == IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&pBaseTexture) && pBaseTexture != NULL) {
898             TRACE("Making container dirty\n");
899             IWineD3DBaseTexture_SetDirty(pBaseTexture, TRUE);
900             IWineD3DBaseTexture_Release(pBaseTexture);
901         } else {
902             TRACE("Surface is standalone, no need to dirty the container\n");
903         }
904     }
905
906     TRACE("returning memory@%p, pitch(%d) dirtyfied(%d)\n", pLockedRect->pBits, pLockedRect->Pitch,
907           This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
908     return WINED3D_OK;
909 }
910
911 static void flush_to_framebuffer_drawpixels(IWineD3DSurfaceImpl *This) {
912     GLint  prev_store;
913     GLint  prev_rasterpos[4];
914     GLint skipBytes = 0;
915     BOOL storechanged = FALSE, memory_allocated = FALSE;
916     GLint fmt, type;
917     BYTE *mem;
918     UINT bpp;
919     UINT pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);    /* target is argb, 4 byte */
920
921     glDisable(GL_TEXTURE_2D);
922     vcheckGLcall("glDisable(GL_TEXTURE_2D)");
923
924     glFlush();
925     vcheckGLcall("glFlush");
926     glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
927     vcheckGLcall("glIntegerv");
928     glGetIntegerv(GL_CURRENT_RASTER_POSITION, &prev_rasterpos[0]);
929     vcheckGLcall("glIntegerv");
930     glPixelZoom(1.0, -1.0);
931     vcheckGLcall("glPixelZoom");
932
933     /* If not fullscreen, we need to skip a number of bytes to find the next row of data */
934     glGetIntegerv(GL_UNPACK_ROW_LENGTH, &skipBytes);
935     glPixelStorei(GL_UNPACK_ROW_LENGTH, This->currentDesc.Width);
936
937     glRasterPos3i(This->lockedRect.left, This->lockedRect.top, 1);
938     vcheckGLcall("glRasterPos2f");
939
940     /* Some drivers(radeon dri, others?) don't like exceptions during
941      * glDrawPixels. If the surface is a DIB section, it might be in GDIMode
942      * after ReleaseDC. Reading it will cause an exception, which x11drv will
943      * catch to put the dib section in InSync mode, which leads to a crash
944      * and a blocked x server on my radeon card.
945      *
946      * The following lines read the dib section so it is put in inSync mode
947      * before glDrawPixels is called and the crash is prevented. There won't
948      * be any interfering gdi accesses, because UnlockRect is called from
949      * ReleaseDC, and the app won't use the dc any more afterwards.
950      */
951     if(This->Flags & SFLAG_DIBSECTION) {
952         volatile BYTE read;
953         read = This->resource.allocatedMemory[0];
954     }
955
956     switch (This->resource.format) {
957         /* No special care needed */
958         case WINED3DFMT_A4R4G4B4:
959         case WINED3DFMT_R5G6B5:
960         case WINED3DFMT_A1R5G5B5:
961         case WINED3DFMT_R8G8B8:
962             type = This->glDescription.glType;
963             fmt = This->glDescription.glFormat;
964             mem = This->resource.allocatedMemory;
965             bpp = This->bytesPerPixel;
966             break;
967
968         case WINED3DFMT_X4R4G4B4:
969         {
970             int size;
971             unsigned short *data;
972             data = (unsigned short *)This->resource.allocatedMemory;
973             size = (This->lockedRect.bottom - This->lockedRect.top) * (This->lockedRect.right - This->lockedRect.left);
974             while(size > 0) {
975                 *data |= 0xF000;
976                 data++;
977                 size--;
978             }
979             type = This->glDescription.glType;
980             fmt = This->glDescription.glFormat;
981             mem = This->resource.allocatedMemory;
982             bpp = This->bytesPerPixel;
983         }
984         break;
985
986         case WINED3DFMT_X1R5G5B5:
987         {
988             int size;
989             unsigned short *data;
990             data = (unsigned short *)This->resource.allocatedMemory;
991             size = (This->lockedRect.bottom - This->lockedRect.top) * (This->lockedRect.right - This->lockedRect.left);
992             while(size > 0) {
993                 *data |= 0x8000;
994                 data++;
995                 size--;
996             }
997             type = This->glDescription.glType;
998             fmt = This->glDescription.glFormat;
999             mem = This->resource.allocatedMemory;
1000             bpp = This->bytesPerPixel;
1001         }
1002         break;
1003
1004         case WINED3DFMT_X8R8G8B8:
1005         {
1006             /* make sure the X byte is set to alpha on, since it 
1007                could be any random value. This fixes the intro movie in Pirates! */
1008             int size;
1009             unsigned int *data;
1010             data = (unsigned int *)This->resource.allocatedMemory;
1011             size = (This->lockedRect.bottom - This->lockedRect.top) * (This->lockedRect.right - This->lockedRect.left);
1012             while(size > 0) {
1013                 *data |= 0xFF000000;
1014                 data++;
1015                 size--;
1016             }
1017         }
1018         /* Fall through */
1019
1020         case WINED3DFMT_A8R8G8B8:
1021         {
1022             glPixelStorei(GL_PACK_SWAP_BYTES, TRUE);
1023             vcheckGLcall("glPixelStorei");
1024             storechanged = TRUE;
1025             type = This->glDescription.glType;
1026             fmt = This->glDescription.glFormat;
1027             mem = This->resource.allocatedMemory;
1028             bpp = This->bytesPerPixel;
1029         }
1030         break;
1031
1032         case WINED3DFMT_A2R10G10B10:
1033         {
1034             glPixelStorei(GL_PACK_SWAP_BYTES, TRUE);
1035             vcheckGLcall("glPixelStorei");
1036             storechanged = TRUE;
1037             type = This->glDescription.glType;
1038             fmt = This->glDescription.glFormat;
1039             mem = This->resource.allocatedMemory;
1040             bpp = This->bytesPerPixel;
1041         }
1042         break;
1043
1044         case WINED3DFMT_P8:
1045         {
1046             int height = This->glRect.bottom - This->glRect.top;
1047             type = GL_UNSIGNED_BYTE;
1048             fmt = GL_RGBA;
1049
1050             mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * sizeof(DWORD));
1051             if(!mem) {
1052                 ERR("Out of memory\n");
1053                 return;
1054             }
1055             memory_allocated = TRUE;
1056             d3dfmt_convert_surface(This->resource.allocatedMemory,
1057                                    mem,
1058                                    pitch,
1059                                    pitch,
1060                                    height,
1061                                    pitch * 4,
1062                                    CONVERT_PALETTED,
1063                                    This);
1064             bpp = This->bytesPerPixel * 4;
1065             pitch *= 4;
1066         }
1067         break;
1068
1069         default:
1070             FIXME("Unsupported Format %u in locking func\n", This->resource.format);
1071
1072             /* Give it a try */
1073             type = This->glDescription.glType;
1074             fmt = This->glDescription.glFormat;
1075             mem = This->resource.allocatedMemory;
1076             bpp = This->bytesPerPixel;
1077     }
1078
1079     glDrawPixels(This->lockedRect.right - This->lockedRect.left,
1080                  (This->lockedRect.bottom - This->lockedRect.top)-1,
1081                  fmt, type,
1082                  mem + bpp * This->lockedRect.left + pitch * This->lockedRect.top);
1083     checkGLcall("glDrawPixels");
1084     glPixelZoom(1.0,1.0);
1085     vcheckGLcall("glPixelZoom");
1086
1087     glRasterPos3iv(&prev_rasterpos[0]);
1088     vcheckGLcall("glRasterPos3iv");
1089
1090     /* Reset to previous pack row length */
1091     glPixelStorei(GL_UNPACK_ROW_LENGTH, skipBytes);
1092     vcheckGLcall("glPixelStorei GL_UNPACK_ROW_LENGTH");
1093     if(storechanged) {
1094         glPixelStorei(GL_PACK_SWAP_BYTES, prev_store);
1095         vcheckGLcall("glPixelStorei GL_PACK_SWAP_BYTES");
1096     }
1097
1098     /* Blitting environment requires that 2D texturing is enabled. It was turned off before,
1099      * turn it on again
1100      */
1101     glEnable(GL_TEXTURE_2D);
1102     checkGLcall("glEnable(GL_TEXTURE_2D)");
1103
1104     if(memory_allocated) HeapFree(GetProcessHeap(), 0, mem);
1105     return;
1106 }
1107
1108 static void flush_to_framebuffer_texture(IWineD3DSurfaceImpl *This) {
1109     float glTexCoord[4];
1110
1111     glTexCoord[0] = (float) This->lockedRect.left   / (float) This->pow2Width; /* left */
1112     glTexCoord[1] = (float) This->lockedRect.right  / (float) This->pow2Width; /* right */
1113     glTexCoord[2] = (float) This->lockedRect.top    / (float) This->pow2Height; /* top */
1114     glTexCoord[3] = (float) This->lockedRect.bottom / (float) This->pow2Height; /* bottom */
1115
1116     IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
1117
1118     ENTER_GL();
1119
1120     glBindTexture(GL_TEXTURE_2D, This->glDescription.textureName);
1121     checkGLcall("glEnable glBindTexture");
1122
1123     /* No filtering for blts */
1124     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1125     checkGLcall("glTexParameteri");
1126     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1127     checkGLcall("glTexParameteri");
1128
1129     /* Start drawing a quad */
1130     glBegin(GL_QUADS);
1131
1132     glColor3d(1.0f, 1.0f, 1.0f);
1133     glTexCoord2f(glTexCoord[0], glTexCoord[2]);
1134     glVertex3f(This->lockedRect.left, This->lockedRect.top, 0.0);
1135
1136     glTexCoord2f(glTexCoord[0], glTexCoord[3]);
1137     glVertex3f(This->lockedRect.left, This->lockedRect.bottom, 0.0);
1138
1139     glTexCoord2f(glTexCoord[1], glTexCoord[3]);
1140     glVertex3d(This->lockedRect.right, This->lockedRect.bottom, 0.0);
1141
1142     glTexCoord2f(glTexCoord[1], glTexCoord[2]);
1143     glVertex3f(This->lockedRect.right, This->lockedRect.top, 0.0);
1144
1145     glEnd();
1146     checkGLcall("glEnd");
1147
1148     /* Unbind the texture */
1149     glBindTexture(GL_TEXTURE_2D, 0);
1150     checkGLcall("glEnable glBindTexture");
1151
1152     LEAVE_GL();
1153 }
1154
1155 static HRESULT WINAPI IWineD3DSurfaceImpl_UnlockRect(IWineD3DSurface *iface) {
1156     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1157     IWineD3DDeviceImpl  *myDevice = This->resource.wineD3DDevice;
1158     IWineD3DSwapChainImpl *swapchain = NULL;
1159
1160     if (!(This->Flags & SFLAG_LOCKED)) {
1161         WARN("trying to Unlock an unlocked surf@%p\n", This);
1162         return WINED3DERR_INVALIDCALL;
1163     }
1164
1165     TRACE("(%p) : dirtyfied(%d)\n", This, This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
1166
1167     if (This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE)) {
1168         TRACE("(%p) : Not Dirtified so nothing to do, return now\n", This);
1169         goto unlock_end;
1170     }
1171
1172     IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain);
1173     if(swapchain || iface == myDevice->render_targets[0]) {
1174         if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1175             static BOOL warned = FALSE;
1176             if(!warned) {
1177                 ERR("The application tries to write to the render target, but render target locking is disabled\n");
1178                 warned = TRUE;
1179             }
1180             if(swapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
1181             goto unlock_end;
1182         }
1183
1184         /* Activate the correct context for the render target */
1185         ENTER_GL();
1186         ActivateContext(myDevice, iface, CTXUSAGE_BLIT);
1187
1188         if(!swapchain) {
1189             /* Primary offscreen render target */
1190             TRACE("Offscreen render target\n");
1191             glDrawBuffer(myDevice->offscreenBuffer);
1192             checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
1193         } else {
1194             GLenum buffer = surface_get_gl_buffer(iface, (IWineD3DSwapChain *)swapchain);
1195             TRACE("Unlocking %#x buffer\n", buffer);
1196             glDrawBuffer(buffer);
1197             checkGLcall("glDrawBuffer");
1198
1199             IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapchain);
1200         }
1201
1202         switch(wined3d_settings.rendertargetlock_mode) {
1203             case RTL_AUTO:
1204             case RTL_READDRAW:
1205             case RTL_TEXDRAW:
1206                 flush_to_framebuffer_drawpixels(This);
1207                 break;
1208
1209             case RTL_READTEX:
1210             case RTL_TEXTEX:
1211                 flush_to_framebuffer_texture(This);
1212                 break;
1213         }
1214         if(!swapchain) {
1215             glDrawBuffer(myDevice->offscreenBuffer);
1216             checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
1217         } else if(swapchain->backBuffer) {
1218             glDrawBuffer(GL_BACK);
1219             checkGLcall("glDrawBuffer(GL_BACK)");
1220         } else {
1221             glDrawBuffer(GL_FRONT);
1222             checkGLcall("glDrawBuffer(GL_FRONT)");
1223         }
1224         LEAVE_GL();
1225
1226         This->dirtyRect.left   = This->currentDesc.Width;
1227         This->dirtyRect.top    = This->currentDesc.Height;
1228         This->dirtyRect.right  = 0;
1229         This->dirtyRect.bottom = 0;
1230         This->Flags |= SFLAG_INDRAWABLE;
1231     } else if(iface == myDevice->stencilBufferTarget) {
1232         FIXME("Depth Stencil buffer locking is not implemented\n");
1233     } else {
1234         /* The rest should be a normal texture */
1235         IWineD3DBaseTextureImpl *impl;
1236         /* Check if the texture is bound, if yes dirtify the sampler to force a re-upload of the texture
1237          * Can't load the texture here because PreLoad may destroy and recreate the gl texture, so sampler
1238          * states need resetting
1239          */
1240         if(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&impl) == WINED3D_OK) {
1241             if(impl->baseTexture.bindCount) {
1242                 IWineD3DDeviceImpl_MarkStateDirty(myDevice, STATE_SAMPLER(impl->baseTexture.sampler));
1243             }
1244             IWineD3DBaseTexture_Release((IWineD3DBaseTexture *) impl);
1245         }
1246     }
1247
1248     unlock_end:
1249     This->Flags &= ~SFLAG_LOCKED;
1250     memset(&This->lockedRect, 0, sizeof(RECT));
1251     return WINED3D_OK;
1252 }
1253
1254 HRESULT WINAPI IWineD3DSurfaceImpl_GetDC(IWineD3DSurface *iface, HDC *pHDC) {
1255     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1256     WINED3DLOCKED_RECT lock;
1257     UINT usage;
1258     BITMAPINFO* b_info;
1259     HDC ddc;
1260     DWORD *masks;
1261     HRESULT hr;
1262     RGBQUAD col[256];
1263     const PixelFormatDesc *formatEntry = getFormatDescEntry(This->resource.format);
1264
1265     TRACE("(%p)->(%p)\n",This,pHDC);
1266
1267     if(This->Flags & SFLAG_USERPTR) {
1268         ERR("Not supported on surfaces with an application-provided surfaces\n");
1269         return WINEDDERR_NODC;
1270     }
1271
1272     /* Give more detailed info for ddraw */
1273     if (This->Flags & SFLAG_DCINUSE)
1274         return WINEDDERR_DCALREADYCREATED;
1275
1276     /* Can't GetDC if the surface is locked */
1277     if (This->Flags & SFLAG_LOCKED)
1278         return WINED3DERR_INVALIDCALL;
1279
1280     memset(&lock, 0, sizeof(lock)); /* To be sure */
1281
1282     /* Create a DIB section if there isn't a hdc yet */
1283     if(!This->hDC) {
1284         int extraline = 0;
1285         SYSTEM_INFO sysInfo;
1286         void *oldmem = This->resource.allocatedMemory;
1287
1288         switch (This->bytesPerPixel) {
1289             case 2:
1290             case 4:
1291                 /* Allocate extra space to store the RGB bit masks. */
1292                 b_info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 3 * sizeof(DWORD));
1293                 break;
1294
1295             case 3:
1296                 b_info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER));
1297                 break;
1298
1299             default:
1300                 /* Allocate extra space for a palette. */
1301                 b_info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1302                                   sizeof(BITMAPINFOHEADER)
1303                                   + sizeof(RGBQUAD)
1304                                   * (1 << (This->bytesPerPixel * 8)));
1305                 break;
1306         }
1307
1308         if (!b_info)
1309             return E_OUTOFMEMORY;
1310
1311         /* Some apps access the surface in via DWORDs, and do not take the necessary care at the end of the
1312          * surface. So we need at least extra 4 bytes at the end of the surface. Check against the page size,
1313          * if the last page used for the surface has at least 4 spare bytes we're safe, otherwise
1314          * add an extra line to the dib section
1315          */
1316         GetSystemInfo(&sysInfo);
1317         if( ((This->resource.size + 3) % sysInfo.dwPageSize) < 4) {
1318             extraline = 1;
1319             TRACE("Adding an extra line to the dib section\n");
1320         }
1321
1322         b_info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1323         b_info->bmiHeader.biWidth = This->currentDesc.Width;
1324         b_info->bmiHeader.biHeight = -This->currentDesc.Height -extraline;
1325         b_info->bmiHeader.biSizeImage = ( This->currentDesc.Height + extraline) * IWineD3DSurface_GetPitch(iface);
1326         b_info->bmiHeader.biPlanes = 1;
1327         b_info->bmiHeader.biBitCount = This->bytesPerPixel * 8;
1328
1329         b_info->bmiHeader.biXPelsPerMeter = 0;
1330         b_info->bmiHeader.biYPelsPerMeter = 0;
1331         b_info->bmiHeader.biClrUsed = 0;
1332         b_info->bmiHeader.biClrImportant = 0;
1333
1334         /* Get the bit masks */
1335         masks = (DWORD *) &(b_info->bmiColors);
1336         switch (This->resource.format) {
1337             case WINED3DFMT_R8G8B8:
1338                 usage = DIB_RGB_COLORS;
1339                 b_info->bmiHeader.biCompression = BI_RGB;
1340                 break;
1341
1342             case WINED3DFMT_X1R5G5B5:
1343             case WINED3DFMT_A1R5G5B5:
1344             case WINED3DFMT_A4R4G4B4:
1345             case WINED3DFMT_X4R4G4B4:
1346             case WINED3DFMT_R3G3B2:
1347             case WINED3DFMT_A8R3G3B2:
1348             case WINED3DFMT_A2B10G10R10:
1349             case WINED3DFMT_A8B8G8R8:
1350             case WINED3DFMT_X8B8G8R8:
1351             case WINED3DFMT_A2R10G10B10:
1352             case WINED3DFMT_R5G6B5:
1353             case WINED3DFMT_A16B16G16R16:
1354                 usage = 0;
1355                 b_info->bmiHeader.biCompression = BI_BITFIELDS;
1356                 masks[0] = formatEntry->redMask;
1357                 masks[1] = formatEntry->greenMask;
1358                 masks[2] = formatEntry->blueMask;
1359                 break;
1360
1361             default:
1362                 /* Don't know palette */
1363                 b_info->bmiHeader.biCompression = BI_RGB;
1364                 usage = 0;
1365                 break;
1366         }
1367
1368         ddc = GetDC(0);
1369         if (ddc == 0) {
1370             HeapFree(GetProcessHeap(), 0, b_info);
1371             return HRESULT_FROM_WIN32(GetLastError());
1372         }
1373
1374         TRACE("Creating a DIB section with size %dx%dx%d, size=%d\n", b_info->bmiHeader.biWidth, b_info->bmiHeader.biHeight, b_info->bmiHeader.biBitCount, b_info->bmiHeader.biSizeImage);
1375         This->dib.DIBsection = CreateDIBSection(ddc, b_info, usage, &This->dib.bitmap_data, 0 /* Handle */, 0 /* Offset */);
1376         ReleaseDC(0, ddc);
1377
1378         if (!This->dib.DIBsection) {
1379             ERR("CreateDIBSection failed!\n");
1380             HeapFree(GetProcessHeap(), 0, b_info);
1381             return HRESULT_FROM_WIN32(GetLastError());
1382         }
1383
1384         TRACE("DIBSection at : %p\n", This->dib.bitmap_data);
1385
1386         /* copy the existing surface to the dib section */
1387         if(This->resource.allocatedMemory) {
1388             memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, b_info->bmiHeader.biSizeImage);
1389             /* We won't need that any more */
1390         } else {
1391             /* This is to make LockRect read the gl Texture although memory is allocated */
1392             This->Flags &= ~SFLAG_INSYSMEM;
1393         }
1394
1395         HeapFree(GetProcessHeap(), 0, b_info);
1396
1397         /* Use the dib section from now on */
1398         This->resource.allocatedMemory = This->dib.bitmap_data;
1399
1400         /* Now allocate a HDC */
1401         This->hDC = CreateCompatibleDC(0);
1402         This->dib.holdbitmap = SelectObject(This->hDC, This->dib.DIBsection);
1403         TRACE("using wined3d palette %p\n", This->palette);
1404         SelectPalette(This->hDC,
1405                       This->palette ? This->palette->hpal : 0,
1406                       FALSE);
1407
1408         This->Flags |= SFLAG_DIBSECTION;
1409
1410         if(This->Flags & SFLAG_CLIENT) {
1411             IWineD3DSurface_PreLoad(iface);
1412         }
1413         HeapFree(GetProcessHeap(), 0, oldmem);
1414     }
1415
1416     /* Lock the surface */
1417     hr = IWineD3DSurface_LockRect(iface,
1418                                   &lock,
1419                                   NULL,
1420                                   0);
1421     if(FAILED(hr)) {
1422         ERR("IWineD3DSurface_LockRect failed with hr = %08x\n", hr);
1423         /* keep the dib section */
1424         return hr;
1425     }
1426
1427     if(This->resource.format == WINED3DFMT_P8 ||
1428         This->resource.format == WINED3DFMT_A8P8) {
1429         unsigned int n;
1430         if(This->palette) {
1431             PALETTEENTRY ent[256];
1432
1433             GetPaletteEntries(This->palette->hpal, 0, 256, ent);
1434             for (n=0; n<256; n++) {
1435                 col[n].rgbRed   = ent[n].peRed;
1436                 col[n].rgbGreen = ent[n].peGreen;
1437                 col[n].rgbBlue  = ent[n].peBlue;
1438                 col[n].rgbReserved = 0;
1439             }
1440         } else {
1441             IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1442
1443             for (n=0; n<256; n++) {
1444                 col[n].rgbRed   = device->palettes[device->currentPalette][n].peRed;
1445                 col[n].rgbGreen = device->palettes[device->currentPalette][n].peGreen;
1446                 col[n].rgbBlue  = device->palettes[device->currentPalette][n].peBlue;
1447                 col[n].rgbReserved = 0;
1448             }
1449
1450         }
1451         SetDIBColorTable(This->hDC, 0, 256, col);
1452     }
1453
1454     *pHDC = This->hDC;
1455     TRACE("returning %p\n",*pHDC);
1456     This->Flags |= SFLAG_DCINUSE;
1457
1458     return WINED3D_OK;
1459 }
1460
1461 HRESULT WINAPI IWineD3DSurfaceImpl_ReleaseDC(IWineD3DSurface *iface, HDC hDC) {
1462     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1463
1464     TRACE("(%p)->(%p)\n",This,hDC);
1465
1466     if (!(This->Flags & SFLAG_DCINUSE))
1467         return WINED3DERR_INVALIDCALL;
1468
1469     /* we locked first, so unlock now */
1470     IWineD3DSurface_UnlockRect(iface);
1471
1472     This->Flags &= ~SFLAG_DCINUSE;
1473
1474     return WINED3D_OK;
1475 }
1476
1477 /* ******************************************************
1478    IWineD3DSurface Internal (No mapping to directx api) parts follow
1479    ****************************************************** */
1480
1481 static HRESULT d3dfmt_get_conv(IWineD3DSurfaceImpl *This, BOOL need_alpha_ck, BOOL use_texturing, GLenum *format, GLenum *internal, GLenum *type, CONVERT_TYPES *convert, int *target_bpp) {
1482     BOOL colorkey_active = need_alpha_ck && (This->CKeyFlags & WINEDDSD_CKSRCBLT);
1483     const PixelFormatDesc *formatEntry = getFormatDescEntry(This->resource.format);
1484
1485     /* Default values: From the surface */
1486     *format = formatEntry->glFormat;
1487     *internal = formatEntry->glInternal;
1488     *type = formatEntry->glType;
1489     *convert = NO_CONVERSION;
1490     *target_bpp = This->bytesPerPixel;
1491
1492     /* Ok, now look if we have to do any conversion */
1493     switch(This->resource.format) {
1494         case WINED3DFMT_P8:
1495             /* ****************
1496                 Paletted Texture
1497                 **************** */
1498             /* Use conversion when the paletted texture extension is not available, or when it is available make sure it is used
1499              * for texturing as it won't work for calls like glDraw-/glReadPixels and further also use conversion in case of color keying.
1500              */
1501             if(!GL_SUPPORT(EXT_PALETTED_TEXTURE) || colorkey_active || (!use_texturing && GL_SUPPORT(EXT_PALETTED_TEXTURE)) ) {
1502                 *format = GL_RGBA;
1503                 *internal = GL_RGBA;
1504                 *type = GL_UNSIGNED_BYTE;
1505                 *target_bpp = 4;
1506                 if(colorkey_active) {
1507                     *convert = CONVERT_PALETTED_CK;
1508                 } else {
1509                     *convert = CONVERT_PALETTED;
1510                 }
1511             }
1512
1513             break;
1514
1515         case WINED3DFMT_R3G3B2:
1516             /* **********************
1517                 GL_UNSIGNED_BYTE_3_3_2
1518                 ********************** */
1519             if (colorkey_active) {
1520                 /* This texture format will never be used.. So do not care about color keying
1521                     up until the point in time it will be needed :-) */
1522                 FIXME(" ColorKeying not supported in the RGB 332 format !\n");
1523             }
1524             break;
1525
1526         case WINED3DFMT_R5G6B5:
1527             if (colorkey_active) {
1528                 *convert = CONVERT_CK_565;
1529                 *format = GL_RGBA;
1530                 *internal = GL_RGBA;
1531                 *type = GL_UNSIGNED_SHORT_5_5_5_1;
1532             }
1533             break;
1534
1535         case WINED3DFMT_R8G8B8:
1536             if (colorkey_active) {
1537                 *convert = CONVERT_CK_RGB24;
1538                 *format = GL_RGBA;
1539                 *internal = GL_RGBA;
1540                 *type = GL_UNSIGNED_INT_8_8_8_8;
1541                 *target_bpp = 4;
1542             }
1543             break;
1544
1545         case WINED3DFMT_X8R8G8B8:
1546             if (colorkey_active) {
1547                 *convert = CONVERT_RGB32_888;
1548                 *format = GL_RGBA;
1549                 *internal = GL_RGBA;
1550                 *type = GL_UNSIGNED_INT_8_8_8_8;
1551             }
1552             break;
1553
1554         case WINED3DFMT_V8U8:
1555             if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1556             else if(GL_SUPPORT(ATI_ENVMAP_BUMPMAP)) {
1557                 *format = GL_DUDV_ATI;
1558                 *internal = GL_DU8DV8_ATI;
1559                 *type = GL_BYTE;
1560                 /* No conversion - Just change the gl type */
1561                 break;
1562             }
1563             *convert = CONVERT_V8U8;
1564             *format = GL_BGR;
1565             *internal = GL_RGB8;
1566             *type = GL_UNSIGNED_BYTE;
1567             *target_bpp = 3;
1568             break;
1569
1570         case WINED3DFMT_X8L8V8U8:
1571             if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1572             *convert = CONVERT_X8L8V8U8;
1573             *format = GL_BGRA;
1574             *internal = GL_RGBA8;
1575             *type = GL_UNSIGNED_BYTE;
1576             *target_bpp = 4;
1577             /* Not supported by GL_ATI_envmap_bumpmap */
1578             break;
1579
1580         case WINED3DFMT_Q8W8V8U8:
1581             if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1582             *convert = CONVERT_Q8W8V8U8;
1583             *format = GL_BGRA;
1584             *internal = GL_RGBA8;
1585             *type = GL_UNSIGNED_BYTE;
1586             *target_bpp = 4;
1587             /* Not supported by GL_ATI_envmap_bumpmap */
1588             break;
1589
1590         case WINED3DFMT_V16U16:
1591             if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1592             *convert = CONVERT_V16U16;
1593             *format = GL_BGR;
1594             *internal = GL_RGB16;
1595             *type = GL_SHORT;
1596             *target_bpp = 6;
1597             /* What should I do here about GL_ATI_envmap_bumpmap?
1598              * Convert it or allow data loss by loading it into a 8 bit / channel texture?
1599              */
1600             break;
1601
1602         default:
1603             break;
1604     }
1605
1606     return WINED3D_OK;
1607 }
1608
1609 HRESULT d3dfmt_convert_surface(BYTE *src, BYTE *dst, UINT pitch, UINT width, UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *surf) {
1610     BYTE *source, *dest;
1611     TRACE("(%p)->(%p),(%d,%d,%d,%d,%p)\n", src, dst, pitch, height, outpitch, convert, surf);
1612
1613     switch (convert) {
1614         case NO_CONVERSION:
1615         {
1616             memcpy(dst, src, pitch * height);
1617             break;
1618         }
1619         case CONVERT_PALETTED:
1620         case CONVERT_PALETTED_CK:
1621         {
1622             IWineD3DPaletteImpl* pal = surf->palette;
1623             BYTE table[256][4];
1624             unsigned int i;
1625             unsigned int x, y;
1626
1627             if( pal == NULL) {
1628                 /* TODO: If we are a sublevel, try to get the palette from level 0 */
1629             }
1630
1631             if (pal == NULL) {
1632                 /* Still no palette? Use the device's palette */
1633                 /* Get the surface's palette */
1634                 for (i = 0; i < 256; i++) {
1635                     IWineD3DDeviceImpl *device = surf->resource.wineD3DDevice;
1636
1637                     table[i][0] = device->palettes[device->currentPalette][i].peRed;
1638                     table[i][1] = device->palettes[device->currentPalette][i].peGreen;
1639                     table[i][2] = device->palettes[device->currentPalette][i].peBlue;
1640                     if ((convert == CONVERT_PALETTED_CK) &&
1641                         (i >= surf->SrcBltCKey.dwColorSpaceLowValue) &&
1642                         (i <= surf->SrcBltCKey.dwColorSpaceHighValue)) {
1643                         /* We should maybe here put a more 'neutral' color than the standard bright purple
1644                           one often used by application to prevent the nice purple borders when bi-linear
1645                           filtering is on */
1646                         table[i][3] = 0x00;
1647                     } else {
1648                         table[i][3] = 0xFF;
1649                     }
1650                 }
1651             } else {
1652                 TRACE("Using surface palette %p\n", pal);
1653                 /* Get the surface's palette */
1654                 for (i = 0; i < 256; i++) {
1655                     table[i][0] = pal->palents[i].peRed;
1656                     table[i][1] = pal->palents[i].peGreen;
1657                     table[i][2] = pal->palents[i].peBlue;
1658                     if ((convert == CONVERT_PALETTED_CK) &&
1659                         (i >= surf->SrcBltCKey.dwColorSpaceLowValue) &&
1660                         (i <= surf->SrcBltCKey.dwColorSpaceHighValue)) {
1661                         /* We should maybe here put a more 'neutral' color than the standard bright purple
1662                           one often used by application to prevent the nice purple borders when bi-linear
1663                           filtering is on */
1664                         table[i][3] = 0x00;
1665                     } else if(pal->Flags & WINEDDPCAPS_ALPHA) {
1666                         table[i][3] = pal->palents[i].peFlags;
1667                     } else {
1668                         table[i][3] = 0xFF;
1669                     }
1670                 }
1671             }
1672
1673             for (y = 0; y < height; y++)
1674             {
1675                 source = src + pitch * y;
1676                 dest = dst + outpitch * y;
1677                 /* This is an 1 bpp format, using the width here is fine */
1678                 for (x = 0; x < width; x++) {
1679                     BYTE color = *source++;
1680                     *dest++ = table[color][0];
1681                     *dest++ = table[color][1];
1682                     *dest++ = table[color][2];
1683                     *dest++ = table[color][3];
1684                 }
1685             }
1686         }
1687         break;
1688
1689         case CONVERT_CK_565:
1690         {
1691             /* Converting the 565 format in 5551 packed to emulate color-keying.
1692
1693               Note : in all these conversion, it would be best to average the averaging
1694                       pixels to get the color of the pixel that will be color-keyed to
1695                       prevent 'color bleeding'. This will be done later on if ever it is
1696                       too visible.
1697
1698               Note2: Nvidia documents say that their driver does not support alpha + color keying
1699                      on the same surface and disables color keying in such a case
1700             */
1701             unsigned int x, y;
1702             WORD *Source;
1703             WORD *Dest;
1704
1705             TRACE("Color keyed 565\n");
1706
1707             for (y = 0; y < height; y++) {
1708                 Source = (WORD *) (src + y * pitch);
1709                 Dest = (WORD *) (dst + y * outpitch);
1710                 for (x = 0; x < width; x++ ) {
1711                     WORD color = *Source++;
1712                     *Dest = ((color & 0xFFC0) | ((color & 0x1F) << 1));
1713                     if ((color < surf->SrcBltCKey.dwColorSpaceLowValue) ||
1714                         (color > surf->SrcBltCKey.dwColorSpaceHighValue)) {
1715                         *Dest |= 0x0001;
1716                     }
1717                     Dest++;
1718                 }
1719             }
1720         }
1721         break;
1722
1723         case CONVERT_V8U8:
1724         {
1725             unsigned int x, y;
1726             short *Source;
1727             unsigned char *Dest;
1728             for(y = 0; y < height; y++) {
1729                 Source = (short *) (src + y * pitch);
1730                 Dest = (unsigned char *) (dst + y * outpitch);
1731                 for (x = 0; x < width; x++ ) {
1732                     long color = (*Source++);
1733                     /* B */ Dest[0] = 0xff;
1734                     /* G */ Dest[1] = (color >> 8) + 128; /* V */
1735                     /* R */ Dest[2] = (color) + 128;      /* U */
1736                     Dest += 3;
1737                 }
1738             }
1739             break;
1740         }
1741
1742         case CONVERT_Q8W8V8U8:
1743         {
1744             unsigned int x, y;
1745             DWORD *Source;
1746             unsigned char *Dest;
1747             for(y = 0; y < height; y++) {
1748                 Source = (DWORD *) (src + y * pitch);
1749                 Dest = (unsigned char *) (dst + y * outpitch);
1750                 for (x = 0; x < width; x++ ) {
1751                     long color = (*Source++);
1752                     /* B */ Dest[0] = ((color >> 16) & 0xff) + 128; /* W */
1753                     /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
1754                     /* R */ Dest[2] = (color         & 0xff) + 128; /* U */
1755                     /* A */ Dest[3] = ((color >> 24) & 0xff) + 128; /* Q */
1756                     Dest += 4;
1757                 }
1758             }
1759             break;
1760         }
1761
1762         default:
1763             ERR("Unsupported conversation type %d\n", convert);
1764     }
1765     return WINED3D_OK;
1766 }
1767
1768 /* This function is used in case of 8bit paletted textures to upload the palette.
1769    For now it only supports GL_EXT_paletted_texture extension but support for other
1770    extensions like ARB_fragment_program and ATI_fragment_shaders will be added as well.
1771 */
1772 static void d3dfmt_p8_upload_palette(IWineD3DSurface *iface, CONVERT_TYPES convert) {
1773     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1774     IWineD3DPaletteImpl* pal = This->palette;
1775     BYTE table[256][4];
1776     int i;
1777
1778     if (pal == NULL) {
1779         /* Still no palette? Use the device's palette */
1780         /* Get the surface's palette */
1781         for (i = 0; i < 256; i++) {
1782             IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1783
1784             table[i][0] = device->palettes[device->currentPalette][i].peRed;
1785             table[i][1] = device->palettes[device->currentPalette][i].peGreen;
1786             table[i][2] = device->palettes[device->currentPalette][i].peBlue;
1787             if ((convert == CONVERT_PALETTED_CK) &&
1788                 (i >= This->SrcBltCKey.dwColorSpaceLowValue) &&
1789                 (i <= This->SrcBltCKey.dwColorSpaceHighValue)) {
1790                 /* We should maybe here put a more 'neutral' color than the standard bright purple
1791                    one often used by application to prevent the nice purple borders when bi-linear
1792                    filtering is on */
1793                 table[i][3] = 0x00;
1794             } else {
1795                 table[i][3] = 0xFF;
1796             }
1797         }
1798     } else {
1799         TRACE("Using surface palette %p\n", pal);
1800         /* Get the surface's palette */
1801         for (i = 0; i < 256; i++) {
1802             table[i][0] = pal->palents[i].peRed;
1803             table[i][1] = pal->palents[i].peGreen;
1804             table[i][2] = pal->palents[i].peBlue;
1805             if ((convert == CONVERT_PALETTED_CK) &&
1806                 (i >= This->SrcBltCKey.dwColorSpaceLowValue) &&
1807                 (i <= This->SrcBltCKey.dwColorSpaceHighValue)) {
1808                 /* We should maybe here put a more 'neutral' color than the standard bright purple
1809                    one often used by application to prevent the nice purple borders when bi-linear
1810                    filtering is on */
1811                 table[i][3] = 0x00;
1812             } else if(pal->Flags & WINEDDPCAPS_ALPHA) {
1813                 table[i][3] = pal->palents[i].peFlags;
1814             } else {
1815                 table[i][3] = 0xFF;
1816             }
1817         }
1818     }
1819     GL_EXTCALL(glColorTableEXT(GL_TEXTURE_2D,GL_RGBA,256,GL_RGBA,GL_UNSIGNED_BYTE, table));
1820 }
1821
1822 static BOOL palette9_changed(IWineD3DSurfaceImpl *This) {
1823     IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1824
1825     if(This->palette || (This->resource.format != WINED3DFMT_P8 && This->resource.format != WINED3DFMT_A8P8)) {
1826         /* If a ddraw-style palette is attached assume no d3d9 palette change.
1827          * Also the palette isn't interesting if the surface format isn't P8 or A8P8
1828          */
1829         return FALSE;
1830     }
1831
1832     if(This->palette9) {
1833         if(memcmp(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256) == 0) {
1834             return FALSE;
1835         }
1836     } else {
1837         This->palette9 = (PALETTEENTRY *) HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
1838     }
1839     memcpy(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256);
1840     return TRUE;
1841 }
1842
1843 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadTexture(IWineD3DSurface *iface) {
1844     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1845     IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1846     GLenum format, internal, type;
1847     CONVERT_TYPES convert;
1848     int bpp;
1849     int width, pitch, outpitch;
1850     BYTE *mem;
1851
1852     if (!(This->Flags & SFLAG_INTEXTURE)) {
1853         TRACE("Reloading because surface is dirty\n");
1854     } else if(/* Reload: gl texture has ck, now no ckey is set OR */
1855               ((This->Flags & SFLAG_GLCKEY) && (!(This->CKeyFlags & WINEDDSD_CKSRCBLT))) ||
1856               /* Reload: vice versa  OR */
1857               ((!(This->Flags & SFLAG_GLCKEY)) && (This->CKeyFlags & WINEDDSD_CKSRCBLT)) ||
1858               /* Also reload: Color key is active AND the color key has changed */
1859               ((This->CKeyFlags & WINEDDSD_CKSRCBLT) && (
1860                 (This->glCKey.dwColorSpaceLowValue != This->SrcBltCKey.dwColorSpaceLowValue) ||
1861                 (This->glCKey.dwColorSpaceHighValue != This->SrcBltCKey.dwColorSpaceHighValue)))) {
1862         TRACE("Reloading because of color keying\n");
1863     } else if(palette9_changed(This)) {
1864         TRACE("Reloading surface because the d3d8/9 palette was changed\n");
1865     } else {
1866         TRACE("surface is already in texture\n");
1867         return WINED3D_OK;
1868     }
1869
1870     This->Flags |= SFLAG_INTEXTURE;
1871
1872     /* Resources are placed in system RAM and do not need to be recreated when a device is lost.
1873     *  These resources are not bound by device size or format restrictions. Because of this,
1874     *  these resources cannot be accessed by the Direct3D device nor set as textures or render targets.
1875     *  However, these resources can always be created, locked, and copied.
1876     */
1877     if (This->resource.pool == WINED3DPOOL_SCRATCH )
1878     {
1879         FIXME("(%p) Operation not supported for scratch textures\n",This);
1880         return WINED3DERR_INVALIDCALL;
1881     }
1882
1883     d3dfmt_get_conv(This, TRUE /* We need color keying */, TRUE /* We will use textures */, &format, &internal, &type, &convert, &bpp);
1884
1885     if (This->Flags & SFLAG_INDRAWABLE) {
1886         if (This->glDescription.level != 0)
1887             FIXME("Surface in texture is only supported for level 0\n");
1888         else if (This->resource.format == WINED3DFMT_P8 || This->resource.format == WINED3DFMT_A8P8 ||
1889                  This->resource.format == WINED3DFMT_DXT1 || This->resource.format == WINED3DFMT_DXT2 ||
1890                  This->resource.format == WINED3DFMT_DXT3 || This->resource.format == WINED3DFMT_DXT4 ||
1891                  This->resource.format == WINED3DFMT_DXT5)
1892             FIXME("Format %d not supported\n", This->resource.format);
1893         else {
1894             GLint prevRead;
1895
1896             ENTER_GL();
1897             glGetIntegerv(GL_READ_BUFFER, &prevRead);
1898             vcheckGLcall("glGetIntegerv");
1899             glReadBuffer(This->resource.wineD3DDevice->offscreenBuffer);
1900             vcheckGLcall("glReadBuffer");
1901
1902             if(!(This->Flags & SFLAG_ALLOCATED)) {
1903                 surface_allocate_surface(This, internal, This->pow2Width,
1904                                          This->pow2Height, format, type);
1905             }
1906
1907             glCopyTexSubImage2D(This->glDescription.target,
1908                                 This->glDescription.level,
1909                                 0, 0, 0, 0,
1910                                 This->currentDesc.Width,
1911                                 This->currentDesc.Height);
1912             checkGLcall("glCopyTexSubImage2D");
1913
1914             glReadBuffer(prevRead);
1915             vcheckGLcall("glReadBuffer");
1916
1917             LEAVE_GL();
1918
1919             TRACE("Updated target %d\n", This->glDescription.target);
1920         }
1921         return WINED3D_OK;
1922     } else
1923         /* The only place where LoadTexture() might get called when isInDraw=1
1924          * is ActivateContext where lastActiveRenderTarget is preloaded.
1925          */
1926         if(iface == device->lastActiveRenderTarget && device->isInDraw)
1927             ERR("Reading back render target but SFLAG_INDRAWABLE not set\n");
1928
1929     /* Otherwise: System memory copy must be most up to date */
1930
1931     if(This->CKeyFlags & WINEDDSD_CKSRCBLT) {
1932         This->Flags |= SFLAG_GLCKEY;
1933         This->glCKey = This->SrcBltCKey;
1934     }
1935     else This->Flags &= ~SFLAG_GLCKEY;
1936
1937     /* The width is in 'length' not in bytes */
1938     width = This->currentDesc.Width;
1939     pitch = IWineD3DSurface_GetPitch(iface);
1940
1941     if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
1942         int height = This->currentDesc.Height;
1943
1944         /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
1945         outpitch = width * bpp;
1946         outpitch = (outpitch + SURFACE_ALIGNMENT - 1) & ~(SURFACE_ALIGNMENT - 1);
1947
1948         mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
1949         if(!mem) {
1950             ERR("Out of memory %d, %d!\n", outpitch, height);
1951             return WINED3DERR_OUTOFVIDEOMEMORY;
1952         }
1953         d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
1954
1955         This->Flags |= SFLAG_CONVERTED;
1956     } else if (This->resource.format == WINED3DFMT_P8 && GL_SUPPORT(EXT_PALETTED_TEXTURE)) {
1957         d3dfmt_p8_upload_palette(iface, convert);
1958         This->Flags &= ~SFLAG_CONVERTED;
1959         mem = This->resource.allocatedMemory;
1960     } else {
1961         This->Flags &= ~SFLAG_CONVERTED;
1962         mem = This->resource.allocatedMemory;
1963     }
1964
1965     /* Make sure the correct pitch is used */
1966     glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
1967
1968     if ((This->Flags & SFLAG_NONPOW2) && !(This->Flags & SFLAG_OVERSIZE)) {
1969         TRACE("non power of two support\n");
1970         if(!(This->Flags & SFLAG_ALLOCATED)) {
1971             surface_allocate_surface(This, internal, This->pow2Width, This->pow2Height, format, type);
1972         }
1973         if (mem) {
1974             surface_upload_data(This, This->currentDesc.Width, This->currentDesc.Height, format, type, mem);
1975         }
1976     } else {
1977         /* When making the realloc conditional, keep in mind that GL_APPLE_client_storage may be in use, and This->resource.allocatedMemory
1978          * changed. So also keep track of memory changes. In this case the texture has to be reallocated
1979          */
1980         if(!(This->Flags & SFLAG_ALLOCATED)) {
1981             surface_allocate_surface(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type);
1982         }
1983         if (mem) {
1984             surface_upload_data(This, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type, mem);
1985         }
1986     }
1987
1988     /* Restore the default pitch */
1989     glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1990
1991     if (mem != This->resource.allocatedMemory)
1992         HeapFree(GetProcessHeap(), 0, mem);
1993
1994 #if 0
1995     {
1996         static unsigned int gen = 0;
1997         char buffer[4096];
1998         ++gen;
1999         if ((gen % 10) == 0) {
2000             snprintf(buffer, sizeof(buffer), "/tmp/surface%p_type%u_level%u_%u.ppm", This, This->glDescription.target, This->glDescription.level, gen);
2001             IWineD3DSurfaceImpl_SaveSnapshot(iface, buffer);
2002         }
2003         /*
2004          * debugging crash code
2005          if (gen == 250) {
2006          void** test = NULL;
2007          *test = 0;
2008          }
2009          */
2010     }
2011 #endif
2012
2013     if (!(This->Flags & SFLAG_DONOTFREE)) {
2014         HeapFree(GetProcessHeap(), 0, This->resource.allocatedMemory);
2015         This->resource.allocatedMemory = NULL;
2016         This->Flags &= ~SFLAG_INSYSMEM;
2017     }
2018
2019     return WINED3D_OK;
2020 }
2021
2022 #include <errno.h>
2023 #include <stdio.h>
2024 HRESULT WINAPI IWineD3DSurfaceImpl_SaveSnapshot(IWineD3DSurface *iface, const char* filename) {
2025     FILE* f = NULL;
2026     UINT i, y;
2027     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2028     char *allocatedMemory;
2029     char *textureRow;
2030     IWineD3DSwapChain *swapChain = NULL;
2031     int width, height;
2032     GLuint tmpTexture = 0;
2033     DWORD color;
2034     /*FIXME:
2035     Textures my not be stored in ->allocatedgMemory and a GlTexture
2036     so we should lock the surface before saving a snapshot, or at least check that
2037     */
2038     /* TODO: Compressed texture images can be obtained from the GL in uncompressed form
2039     by calling GetTexImage and in compressed form by calling
2040     GetCompressedTexImageARB.  Queried compressed images can be saved and
2041     later reused by calling CompressedTexImage[123]DARB.  Pre-compressed
2042     texture images do not need to be processed by the GL and should
2043     significantly improve texture loading performance relative to uncompressed
2044     images. */
2045
2046 /* Setup the width and height to be the internal texture width and height. */
2047     width  = This->pow2Width;
2048     height = This->pow2Height;
2049 /* check to see if were a 'virtual' texture e.g. were not a pbuffer of texture were a back buffer*/
2050     IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapChain);
2051
2052     if (This->Flags & SFLAG_INDRAWABLE && !(This->Flags & SFLAG_INTEXTURE)) {
2053         /* if were not a real texture then read the back buffer into a real texture */
2054         /* we don't want to interfere with the back buffer so read the data into a temporary
2055          * texture and then save the data out of the temporary texture
2056          */
2057         GLint prevRead;
2058         ENTER_GL();
2059         TRACE("(%p) Reading render target into texture\n", This);
2060         glEnable(GL_TEXTURE_2D);
2061
2062         glGenTextures(1, &tmpTexture);
2063         glBindTexture(GL_TEXTURE_2D, tmpTexture);
2064
2065         glTexImage2D(GL_TEXTURE_2D,
2066                         0,
2067                         GL_RGBA,
2068                         width,
2069                         height,
2070                         0/*border*/,
2071                         GL_RGBA,
2072                         GL_UNSIGNED_INT_8_8_8_8_REV,
2073                         NULL);
2074
2075         glGetIntegerv(GL_READ_BUFFER, &prevRead);
2076         vcheckGLcall("glGetIntegerv");
2077         glReadBuffer(swapChain ? GL_BACK : This->resource.wineD3DDevice->offscreenBuffer);
2078         vcheckGLcall("glReadBuffer");
2079         glCopyTexImage2D(GL_TEXTURE_2D,
2080                             0,
2081                             GL_RGBA,
2082                             0,
2083                             0,
2084                             width,
2085                             height,
2086                             0);
2087
2088         checkGLcall("glCopyTexImage2D");
2089         glReadBuffer(prevRead);
2090         LEAVE_GL();
2091
2092     } else { /* bind the real texture, and make sure it up to date */
2093         IWineD3DSurface_PreLoad(iface);
2094     }
2095     allocatedMemory = HeapAlloc(GetProcessHeap(), 0, width  * height * 4);
2096     ENTER_GL();
2097     FIXME("Saving texture level %d width %d height %d\n", This->glDescription.level, width, height);
2098     glGetTexImage(GL_TEXTURE_2D,
2099                 This->glDescription.level,
2100                 GL_RGBA,
2101                 GL_UNSIGNED_INT_8_8_8_8_REV,
2102                 allocatedMemory);
2103     checkGLcall("glTexImage2D");
2104     if (tmpTexture) {
2105         glBindTexture(GL_TEXTURE_2D, 0);
2106         glDeleteTextures(1, &tmpTexture);
2107     }
2108     LEAVE_GL();
2109
2110     f = fopen(filename, "w+");
2111     if (NULL == f) {
2112         ERR("opening of %s failed with: %s\n", filename, strerror(errno));
2113         return WINED3DERR_INVALIDCALL;
2114     }
2115 /* Save the dat out to a TGA file because 1: it's an easy raw format, 2: it supports an alpha chanel*/
2116     TRACE("(%p) opened %s with format %s\n", This, filename, debug_d3dformat(This->resource.format));
2117 /* TGA header */
2118     fputc(0,f);
2119     fputc(0,f);
2120     fputc(2,f);
2121     fputc(0,f);
2122     fputc(0,f);
2123     fputc(0,f);
2124     fputc(0,f);
2125     fputc(0,f);
2126     fputc(0,f);
2127     fputc(0,f);
2128     fputc(0,f);
2129     fputc(0,f);
2130 /* short width*/
2131     fwrite(&width,2,1,f);
2132 /* short height */
2133     fwrite(&height,2,1,f);
2134 /* format rgba */
2135     fputc(0x20,f);
2136     fputc(0x28,f);
2137 /* raw data */
2138     /* if  the data is upside down if we've fetched it from a back buffer, so it needs flipping again to make it the correct way up*/
2139     if(swapChain)
2140         textureRow = allocatedMemory + (width * (height - 1) *4);
2141     else
2142         textureRow = allocatedMemory;
2143     for (y = 0 ; y < height; y++) {
2144         for (i = 0; i < width;  i++) {
2145             color = *((DWORD*)textureRow);
2146             fputc((color >> 16) & 0xFF, f); /* B */
2147             fputc((color >>  8) & 0xFF, f); /* G */
2148             fputc((color >>  0) & 0xFF, f); /* R */
2149             fputc((color >> 24) & 0xFF, f); /* A */
2150             textureRow += 4;
2151         }
2152         /* take two rows of the pointer to the texture memory */
2153         if(swapChain)
2154             (textureRow-= width << 3);
2155
2156     }
2157     TRACE("Closing file\n");
2158     fclose(f);
2159
2160     if(swapChain) {
2161         IWineD3DSwapChain_Release(swapChain);
2162     }
2163     HeapFree(GetProcessHeap(), 0, allocatedMemory);
2164     return WINED3D_OK;
2165 }
2166
2167 /**
2168  *   Slightly inefficient way to handle multiple dirty rects but it works :)
2169  */
2170 extern HRESULT WINAPI IWineD3DSurfaceImpl_AddDirtyRect(IWineD3DSurface *iface, CONST RECT* pDirtyRect) {
2171     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2172     IWineD3DBaseTexture *baseTexture = NULL;
2173     This->Flags &= ~(SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
2174     if (NULL != pDirtyRect) {
2175         This->dirtyRect.left   = min(This->dirtyRect.left,   pDirtyRect->left);
2176         This->dirtyRect.top    = min(This->dirtyRect.top,    pDirtyRect->top);
2177         This->dirtyRect.right  = max(This->dirtyRect.right,  pDirtyRect->right);
2178         This->dirtyRect.bottom = max(This->dirtyRect.bottom, pDirtyRect->bottom);
2179     } else {
2180         This->dirtyRect.left   = 0;
2181         This->dirtyRect.top    = 0;
2182         This->dirtyRect.right  = This->currentDesc.Width;
2183         This->dirtyRect.bottom = This->currentDesc.Height;
2184     }
2185     TRACE("(%p) : Dirty: yes, Rect:(%d,%d,%d,%d)\n", This, This->dirtyRect.left,
2186           This->dirtyRect.top, This->dirtyRect.right, This->dirtyRect.bottom);
2187     /* if the container is a basetexture then mark it dirty. */
2188     if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
2189         TRACE("Passing to conatiner\n");
2190         IWineD3DBaseTexture_SetDirty(baseTexture, TRUE);
2191         IWineD3DBaseTexture_Release(baseTexture);
2192     }
2193     return WINED3D_OK;
2194 }
2195
2196 HRESULT WINAPI IWineD3DSurfaceImpl_SetContainer(IWineD3DSurface *iface, IWineD3DBase *container) {
2197     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2198
2199     TRACE("This %p, container %p\n", This, container);
2200
2201     /* We can't keep a reference to the container, since the container already keeps a reference to us. */
2202
2203     TRACE("Setting container to %p from %p\n", container, This->container);
2204     This->container = container;
2205
2206     return WINED3D_OK;
2207 }
2208
2209 HRESULT WINAPI IWineD3DSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format) {
2210     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2211     const PixelFormatDesc *formatEntry = getFormatDescEntry(format);
2212
2213     if (This->resource.format != WINED3DFMT_UNKNOWN) {
2214         FIXME("(%p) : The foramt of the surface must be WINED3DFORMAT_UNKNOWN\n", This);
2215         return WINED3DERR_INVALIDCALL;
2216     }
2217
2218     TRACE("(%p) : Setting texture foramt to (%d,%s)\n", This, format, debug_d3dformat(format));
2219     if (format == WINED3DFMT_UNKNOWN) {
2220         This->resource.size = 0;
2221     } else if (format == WINED3DFMT_DXT1) {
2222         /* DXT1 is half byte per pixel */
2223         This->resource.size = ((max(This->pow2Width, 4) * formatEntry->bpp) * max(This->pow2Height, 4)) >> 1;
2224
2225     } else if (format == WINED3DFMT_DXT2 || format == WINED3DFMT_DXT3 ||
2226                format == WINED3DFMT_DXT4 || format == WINED3DFMT_DXT5) {
2227         This->resource.size = ((max(This->pow2Width, 4) * formatEntry->bpp) * max(This->pow2Height, 4));
2228     } else {
2229         This->resource.size = ((This->pow2Width * formatEntry->bpp) + SURFACE_ALIGNMENT - 1) & ~(SURFACE_ALIGNMENT - 1);
2230         This->resource.size *= This->pow2Height;
2231     }
2232
2233
2234     /* Setup some glformat defaults */
2235     This->glDescription.glFormat         = formatEntry->glFormat;
2236     This->glDescription.glFormatInternal = formatEntry->glInternal;
2237     This->glDescription.glType           = formatEntry->glType;
2238
2239     if (format != WINED3DFMT_UNKNOWN) {
2240         This->bytesPerPixel = formatEntry->bpp;
2241     } else {
2242         This->bytesPerPixel = 0;
2243     }
2244
2245     This->Flags |= (WINED3DFMT_D16_LOCKABLE == format) ? SFLAG_LOCKABLE : 0;
2246     This->Flags &= ~SFLAG_ALLOCATED;
2247
2248     This->resource.format = format;
2249
2250     TRACE("(%p) : Size %d, bytesPerPixel %d, glFormat %d, glFotmatInternal %d, glType %d\n", This, This->resource.size, This->bytesPerPixel, This->glDescription.glFormat, This->glDescription.glFormatInternal, This->glDescription.glType);
2251
2252     return WINED3D_OK;
2253 }
2254
2255 HRESULT WINAPI IWineD3DSurfaceImpl_SetMem(IWineD3DSurface *iface, void *Mem) {
2256     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
2257
2258     /* Render targets depend on their hdc, and we can't create a hdc on a user pointer */
2259     if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
2260         ERR("Not supported on render targets\n");
2261         return WINED3DERR_INVALIDCALL;
2262     }
2263
2264     if(This->Flags & (SFLAG_LOCKED | SFLAG_DCINUSE)) {
2265         WARN("Surface is locked or the HDC is in use\n");
2266         return WINED3DERR_INVALIDCALL;
2267     }
2268
2269     if(Mem && Mem != This->resource.allocatedMemory) {
2270         void *release = NULL;
2271
2272         /* Do I have to copy the old surface content? */
2273         if(This->Flags & SFLAG_DIBSECTION) {
2274                 /* Release the DC. No need to hold the critical section for the update
2275                  * Thread because this thread runs only on front buffers, but this method
2276                  * fails for render targets in the check above.
2277                  */
2278                 SelectObject(This->hDC, This->dib.holdbitmap);
2279                 DeleteDC(This->hDC);
2280                 /* Release the DIB section */
2281                 DeleteObject(This->dib.DIBsection);
2282                 This->dib.bitmap_data = NULL;
2283                 This->resource.allocatedMemory = NULL;
2284                 This->hDC = NULL;
2285                 This->Flags &= ~SFLAG_DIBSECTION;
2286         } else if(!(This->Flags & SFLAG_USERPTR)) {
2287             release = This->resource.allocatedMemory;
2288         }
2289         This->resource.allocatedMemory = Mem;
2290         This->Flags |= SFLAG_USERPTR | SFLAG_INSYSMEM;
2291
2292         /* Now the surface memory is most up do date. Invalidate drawable and texture */
2293         This->Flags &= ~(SFLAG_INDRAWABLE | SFLAG_INTEXTURE);
2294
2295         /* For client textures opengl has to be notified */
2296         if(This->Flags & SFLAG_CLIENT) {
2297             This->Flags &= ~SFLAG_ALLOCATED;
2298             IWineD3DSurface_PreLoad(iface);
2299             /* And hope that the app behaves correctly and did not free the old surface memory before setting a new pointer */
2300         }
2301
2302         /* Now free the old memory if any */
2303         HeapFree(GetProcessHeap(), 0, release);
2304     } else if(This->Flags & SFLAG_USERPTR) {
2305         /* Lockrect and GetDC will re-create the dib section and allocated memory */
2306         This->resource.allocatedMemory = NULL;
2307         This->Flags &= ~SFLAG_USERPTR;
2308
2309         if(This->Flags & SFLAG_CLIENT) {
2310             This->Flags &= ~SFLAG_ALLOCATED;
2311             /* This respecifies an empty texture and opengl knows that the old memory is gone */
2312             IWineD3DSurface_PreLoad(iface);
2313         }
2314     }
2315     return WINED3D_OK;
2316 }
2317
2318 static HRESULT WINAPI IWineD3DSurfaceImpl_Flip(IWineD3DSurface *iface, IWineD3DSurface *override, DWORD Flags) {
2319     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2320     IWineD3DDevice *D3D = (IWineD3DDevice *) This->resource.wineD3DDevice;
2321     TRACE("(%p)->(%p,%x)\n", This, override, Flags);
2322
2323     /* Flipping is only supported on RenderTargets */
2324     if( !(This->resource.usage & WINED3DUSAGE_RENDERTARGET) ) return WINEDDERR_NOTFLIPPABLE;
2325
2326     if(override) {
2327         /* DDraw sets this for the X11 surfaces, so don't confuse the user 
2328          * FIXME("(%p) Target override is not supported by now\n", This);
2329          * Additionally, it isn't really possible to support triple-buffering
2330          * properly on opengl at all
2331          */
2332     }
2333
2334     /* Flipping a OpenGL surface -> Use WineD3DDevice::Present */
2335     return IWineD3DDevice_Present(D3D, NULL, NULL, 0, NULL);
2336 }
2337
2338 /* Does a direct frame buffer -> texture copy. Stretching is done
2339  * with single pixel copy calls
2340  */
2341 static inline void fb_copy_to_texture_direct(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface, IWineD3DSwapChainImpl *swapchain, WINED3DRECT *srect, WINED3DRECT *drect, BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter) {
2342     IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2343     float xrel, yrel;
2344     UINT row;
2345     IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2346
2347     ENTER_GL();
2348
2349     ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
2350
2351     /* Bind the target texture */
2352     glBindTexture(GL_TEXTURE_2D, This->glDescription.textureName);
2353     checkGLcall("glBindTexture");
2354     if(!swapchain) {
2355         glReadBuffer(myDevice->offscreenBuffer);
2356     } else {
2357         GLenum buffer = surface_get_gl_buffer(SrcSurface, (IWineD3DSwapChain *)swapchain);
2358         glReadBuffer(buffer);
2359     }
2360     checkGLcall("glReadBuffer");
2361
2362     xrel = (float) (srect->x2 - srect->x1) / (float) (drect->x2 - drect->x1);
2363     yrel = (float) (srect->y2 - srect->y1) / (float) (drect->y2 - drect->y1);
2364
2365     if( (xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) {
2366         FIXME("Doing a pixel by pixel copy from the framebuffer to a texture, expect major performance issues\n");
2367
2368         if(Filter != WINED3DTEXF_NONE) {
2369             ERR("Texture filtering not supported in direct blit\n");
2370         }
2371     } else if((Filter != WINED3DTEXF_NONE) && ((yrel - 1.0 < -eps) || (yrel - 1.0 > eps))) {
2372         ERR("Texture filtering not supported in direct blit\n");
2373     }
2374
2375     if(upsidedown &&
2376        !((xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) &&
2377        !((yrel - 1.0 < -eps) || (yrel - 1.0 > eps))) {
2378         /* Upside down copy without stretching is nice, one glCopyTexSubImage call will do */
2379
2380         glCopyTexSubImage2D(This->glDescription.target,
2381                             This->glDescription.level,
2382                             drect->x1, drect->y1, /* xoffset, yoffset */
2383                             srect->x1, Src->currentDesc.Height - srect->y2,
2384                             drect->x2 - drect->x1, drect->y2 - drect->y1);
2385     } else {
2386         UINT yoffset = Src->currentDesc.Height - srect->y1 + drect->y1 - 1;
2387         /* I have to process this row by row to swap the image,
2388          * otherwise it would be upside down, so streching in y direction
2389          * doesn't cost extra time
2390          *
2391          * However, streching in x direction can be avoided if not necessary
2392          */
2393         for(row = drect->y1; row < drect->y2; row++) {
2394             if( (xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) {
2395                 /* Well, that stuff works, but it's very slow.
2396                  * find a better way instead
2397                  */
2398                 UINT col;
2399
2400                 for(col = drect->x1; col < drect->x2; col++) {
2401                     glCopyTexSubImage2D(This->glDescription.target,
2402                                         This->glDescription.level,
2403                                         drect->x1 + col, row, /* xoffset, yoffset */
2404                                         srect->x1 + col * xrel, yoffset - (int) (row * yrel),
2405                                         1, 1);
2406                 }
2407             } else {
2408                 glCopyTexSubImage2D(This->glDescription.target,
2409                                     This->glDescription.level,
2410                                     drect->x1, row, /* xoffset, yoffset */
2411                                     srect->x1, yoffset - (int) (row * yrel),
2412                                     drect->x2-drect->x1, 1);
2413             }
2414         }
2415     }
2416
2417     vcheckGLcall("glCopyTexSubImage2D");
2418     LEAVE_GL();
2419 }
2420
2421 /* Uses the hardware to stretch and flip the image */
2422 static inline void fb_copy_to_texture_hwstretch(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface, IWineD3DSwapChainImpl *swapchain, WINED3DRECT *srect, WINED3DRECT *drect, BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter) {
2423     GLuint src, backup = 0;
2424     IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2425     IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2426     float left, right, top, bottom; /* Texture coordinates */
2427     UINT fbwidth = Src->currentDesc.Width;
2428     UINT fbheight = Src->currentDesc.Height;
2429     GLenum drawBuffer = GL_BACK;
2430
2431     TRACE("Using hwstretch blit\n");
2432     /* Activate the Proper context for reading from the source surface, set it up for blitting */
2433     ENTER_GL();
2434     ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
2435
2436     /* Try to use an aux buffer for drawing the rectangle. This way it doesn't need restoring.
2437      * This way we don't have to wait for the 2nd readback to finish to leave this function.
2438      */
2439     if(GL_LIMITS(aux_buffers) >= 2) {
2440         /* Got more than one aux buffer? Use the 2nd aux buffer */
2441         drawBuffer = GL_AUX1;
2442     } else if((swapchain || myDevice->offscreenBuffer == GL_BACK) && GL_LIMITS(aux_buffers) >= 1) {
2443         /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
2444         drawBuffer = GL_AUX0;
2445     }
2446
2447     if(!swapchain && wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2448         glGenTextures(1, &backup);
2449         checkGLcall("glGenTextures\n");
2450         glBindTexture(GL_TEXTURE_2D, backup);
2451         checkGLcall("glBindTexture(Src->glDescription.target, Src->glDescription.textureName)");
2452     } else {
2453         /* Backup the back buffer and copy the source buffer into a texture to draw an upside down stretched quad. If
2454          * we are reading from the back buffer, the backup can be used as source texture
2455          */
2456         if(Src->glDescription.textureName == 0) {
2457             /* Get it a description */
2458             IWineD3DSurface_PreLoad(SrcSurface);
2459         }
2460         glBindTexture(GL_TEXTURE_2D, Src->glDescription.textureName);
2461         checkGLcall("glBindTexture(Src->glDescription.target, Src->glDescription.textureName)");
2462
2463         /* For now invalidate the texture copy of the back buffer. Drawable and sysmem copy are untouched */
2464         Src->Flags &= ~SFLAG_INTEXTURE;
2465     }
2466
2467     glReadBuffer(GL_BACK);
2468     checkGLcall("glReadBuffer(GL_BACK)");
2469
2470     /* TODO: Only back up the part that will be overwritten */
2471     glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
2472                         0, 0 /* read offsets */,
2473                         0, 0,
2474                         fbwidth,
2475                         fbheight);
2476
2477     checkGLcall("glCopyTexSubImage2D");
2478
2479     /* No issue with overriding these - the sampler is dirty due to blit usage */
2480     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
2481                     stateLookup[WINELOOKUP_MAGFILTER][Filter - minLookup[WINELOOKUP_MAGFILTER]]);
2482     checkGLcall("glTexParameteri");
2483     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
2484                     minMipLookup[Filter][WINED3DTEXF_NONE]);
2485     checkGLcall("glTexParameteri");
2486
2487     if(!swapchain || (IWineD3DSurface *) Src == swapchain->backBuffer[0]) {
2488         src = backup ? backup : Src->glDescription.textureName;
2489     } else {
2490         glReadBuffer(GL_FRONT);
2491         checkGLcall("glReadBuffer(GL_FRONT)");
2492
2493         glGenTextures(1, &src);
2494         checkGLcall("glGenTextures(1, &src)");
2495         glBindTexture(GL_TEXTURE_2D, src);
2496         checkGLcall("glBindTexture(GL_TEXTURE_2D, src)");
2497
2498         /* TODO: Only copy the part that will be read. Use srect->x1, srect->y2 as origin, but with the width watch
2499          * out for power of 2 sizes
2500          */
2501         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Src->pow2Width, Src->pow2Height, 0,
2502                     GL_RGBA, GL_UNSIGNED_BYTE, NULL);
2503         checkGLcall("glTexImage2D");
2504         glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
2505                             0, 0 /* read offsets */,
2506                             0, 0,
2507                             fbwidth,
2508                             fbheight);
2509
2510         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2511         checkGLcall("glTexParameteri");
2512         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2513         checkGLcall("glTexParameteri");
2514
2515         glReadBuffer(GL_BACK);
2516         checkGLcall("glReadBuffer(GL_BACK)");
2517     }
2518     checkGLcall("glEnd and previous");
2519
2520     left = (float) srect->x1 / (float) Src->pow2Width;
2521     right = (float) srect->x2 / (float) Src->pow2Width;
2522
2523     if(upsidedown) {
2524         top = (float) (Src->currentDesc.Height - srect->y1) / (float) Src->pow2Height;
2525         bottom = (float) (Src->currentDesc.Height - srect->y2) / (float) Src->pow2Height;
2526     } else {
2527         top = (float) (Src->currentDesc.Height - srect->y2) / (float) Src->pow2Height;
2528         bottom = (float) (Src->currentDesc.Height - srect->y1) / (float) Src->pow2Height;
2529     }
2530
2531     /* draw the source texture stretched and upside down. The correct surface is bound already */
2532     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
2533     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
2534
2535     glDrawBuffer(drawBuffer);
2536     glReadBuffer(drawBuffer);
2537
2538     glBegin(GL_QUADS);
2539         /* bottom left */
2540         glTexCoord2f(left, bottom);
2541         glVertex2i(0, fbheight);
2542
2543         /* top left */
2544         glTexCoord2f(left, top);
2545         glVertex2i(0, fbheight - drect->y2 - drect->y1);
2546
2547         /* top right */
2548         glTexCoord2f(right, top);
2549         glVertex2i(drect->x2 - drect->x1, fbheight - drect->y2 - drect->y1);
2550
2551         /* bottom right */
2552         glTexCoord2f(right, bottom);
2553         glVertex2i(drect->x2 - drect->x1, fbheight);
2554     glEnd();
2555     checkGLcall("glEnd and previous");
2556
2557     /* Now read the stretched and upside down image into the destination texture */
2558     glBindTexture(This->glDescription.target, This->glDescription.textureName);
2559     checkGLcall("glBindTexture");
2560     glCopyTexSubImage2D(This->glDescription.target,
2561                         0,
2562                         drect->x1, drect->y1, /* xoffset, yoffset */
2563                         0, 0, /* We blitted the image to the origin */
2564                         drect->x2 - drect->x1, drect->y2 - drect->y1);
2565     checkGLcall("glCopyTexSubImage2D");
2566
2567     /* Write the back buffer backup back */
2568     glBindTexture(GL_TEXTURE_2D, backup ? backup : Src->glDescription.textureName);
2569     checkGLcall("glBindTexture(GL_TEXTURE_2D, Src->glDescription.textureName)");
2570
2571     if(drawBuffer == GL_BACK) {
2572         glBegin(GL_QUADS);
2573             /* top left */
2574             glTexCoord2f(0.0, (float) fbheight / (float) Src->pow2Height);
2575             glVertex2i(0, 0);
2576
2577             /* bottom left */
2578             glTexCoord2f(0.0, 0.0);
2579             glVertex2i(0, fbheight);
2580
2581             /* bottom right */
2582             glTexCoord2f((float) fbwidth / (float) Src->pow2Width, 0.0);
2583             glVertex2i(fbwidth, Src->currentDesc.Height);
2584
2585             /* top right */
2586             glTexCoord2f((float) fbwidth / (float) Src->pow2Width, (float) fbheight / (float) Src->pow2Height);
2587             glVertex2i(fbwidth, 0);
2588         glEnd();
2589     } else {
2590         /* Restore the old draw buffer */
2591         glDrawBuffer(GL_BACK);
2592     }
2593
2594     /* Cleanup */
2595     if(src != Src->glDescription.textureName && src != backup) {
2596         glDeleteTextures(1, &src);
2597         checkGLcall("glDeleteTextures(1, &src)");
2598     }
2599     if(backup) {
2600         glDeleteTextures(1, &backup);
2601         checkGLcall("glDeleteTextures(1, &backup)");
2602     }
2603     LEAVE_GL();
2604 }
2605
2606 /* Not called from the VTable */
2607 static HRESULT IWineD3DSurfaceImpl_BltOverride(IWineD3DSurfaceImpl *This, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
2608     WINED3DRECT rect;
2609     IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2610     IWineD3DSwapChainImpl *srcSwapchain = NULL, *dstSwapchain = NULL;
2611     IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2612
2613     TRACE("(%p)->(%p,%p,%p,%08x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
2614
2615     /* Get the swapchain. One of the surfaces has to be a primary surface */
2616     IWineD3DSurface_GetContainer( (IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&dstSwapchain);
2617     if(dstSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) dstSwapchain);
2618     if(Src) {
2619         IWineD3DSurface_GetContainer( (IWineD3DSurface *) Src, &IID_IWineD3DSwapChain, (void **)&srcSwapchain);
2620         if(srcSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) srcSwapchain);
2621     }
2622
2623     /* Early sort out of cases where no render target is used */
2624     if(!dstSwapchain && !srcSwapchain &&
2625         SrcSurface != myDevice->render_targets[0] && This != (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
2626         TRACE("No surface is render target, not using hardware blit. Src = %p, dst = %p\n", Src, This);
2627         return WINED3DERR_INVALIDCALL;
2628     }
2629
2630     /* No destination color keying supported */
2631     if(Flags & (WINEDDBLT_KEYDEST | WINEDDBLT_KEYDESTOVERRIDE)) {
2632         /* Can we support that with glBlendFunc if blitting to the frame buffer? */
2633         TRACE("Destination color key not supported in accelerated Blit, falling back to software\n");
2634         return WINED3DERR_INVALIDCALL;
2635     }
2636
2637     if (DestRect) {
2638         rect.x1 = DestRect->left;
2639         rect.y1 = DestRect->top;
2640         rect.x2 = DestRect->right;
2641         rect.y2 = DestRect->bottom;
2642     } else {
2643         rect.x1 = 0;
2644         rect.y1 = 0;
2645         rect.x2 = This->currentDesc.Width;
2646         rect.y2 = This->currentDesc.Height;
2647     }
2648
2649     /* The only case where both surfaces on a swapchain are supported is a back buffer -> front buffer blit on the same swapchain */
2650     if(dstSwapchain && dstSwapchain == srcSwapchain && dstSwapchain->backBuffer &&
2651        ((IWineD3DSurface *) This == dstSwapchain->frontBuffer) && SrcSurface == dstSwapchain->backBuffer[0]) {
2652         /* Half-life does a Blt from the back buffer to the front buffer,
2653          * Full surface size, no flags... Use present instead
2654          *
2655          * This path will only be entered for d3d7 and ddraw apps, because d3d8/9 offer no way to blit TO the front buffer
2656          */
2657
2658         /* Check rects - IWineD3DDevice_Present doesn't handle them */
2659         while(1)
2660         {
2661             RECT mySrcRect;
2662             TRACE("Looking if a Present can be done... ");
2663             /* Source Rectangle must be full surface */
2664             if( SrcRect ) {
2665                 if(SrcRect->left != 0 || SrcRect->top != 0 ||
2666                    SrcRect->right != Src->currentDesc.Width || SrcRect->bottom != Src->currentDesc.Height) {
2667                     TRACE("No, Source rectangle doesn't match\n");
2668                     break;
2669                 }
2670             }
2671             mySrcRect.left = 0;
2672             mySrcRect.top = 0;
2673             mySrcRect.right = Src->currentDesc.Width;
2674             mySrcRect.bottom = Src->currentDesc.Height;
2675
2676             /* No stretching may occur */
2677             if(mySrcRect.right != rect.x2 - rect.x1 ||
2678                mySrcRect.bottom != rect.y2 - rect.y1) {
2679                 TRACE("No, stretching is done\n");
2680                 break;
2681             }
2682
2683             /* Destination must be full surface or match the clipping rectangle */
2684             if(This->clipper && ((IWineD3DClipperImpl *) This->clipper)->hWnd)
2685             {
2686                 RECT cliprect;
2687                 POINT pos[2];
2688                 GetClientRect(((IWineD3DClipperImpl *) This->clipper)->hWnd, &cliprect);
2689                 pos[0].x = rect.x1;
2690                 pos[0].y = rect.y1;
2691                 pos[1].x = rect.x2;
2692                 pos[1].y = rect.y2;
2693                 MapWindowPoints(GetDesktopWindow(), ((IWineD3DClipperImpl *) This->clipper)->hWnd,
2694                                 pos, 2);
2695
2696                 if(pos[0].x != cliprect.left  || pos[0].y != cliprect.top   ||
2697                    pos[1].x != cliprect.right || pos[1].y != cliprect.bottom)
2698                 {
2699                     TRACE("No, dest rectangle doesn't match(clipper)\n");
2700                     TRACE("Clip rect at (%d,%d)-(%d,%d)\n", cliprect.left, cliprect.top, cliprect.right, cliprect.bottom);
2701                     TRACE("Blt dest: (%d,%d)-(%d,%d)\n", rect.x1, rect.y1, rect.x2, rect.y2);
2702                     break;
2703                 }
2704             }
2705             else
2706             {
2707                 if(rect.x1 != 0 || rect.y1 != 0 ||
2708                    rect.x2 != This->currentDesc.Width || rect.y2 != This->currentDesc.Height) {
2709                     TRACE("No, dest rectangle doesn't match(surface size)\n");
2710                     break;
2711                 }
2712             }
2713
2714             TRACE("Yes\n");
2715
2716             /* These flags are unimportant for the flag check, remove them */
2717             if((Flags & ~(WINEDDBLT_DONOTWAIT | WINEDDBLT_WAIT)) == 0) {
2718                 WINED3DSWAPEFFECT orig_swap = dstSwapchain->presentParms.SwapEffect;
2719
2720                 /* The idea behind this is that a glReadPixels and a glDrawPixels call
2721                     * take very long, while a flip is fast.
2722                     * This applies to Half-Life, which does such Blts every time it finished
2723                     * a frame, and to Prince of Persia 3D, which uses this to draw at least the main
2724                     * menu. This is also used by all apps when they do windowed rendering
2725                     *
2726                     * The problem is that flipping is not really the same as copying. After a
2727                     * Blt the front buffer is a copy of the back buffer, and the back buffer is
2728                     * untouched. Therefore it's necessary to override the swap effect
2729                     * and to set it back after the flip.
2730                     *
2731                     * Windowed Direct3D < 7 apps do the same. The D3D7 sdk demso are nice
2732                     * testcases.
2733                     */
2734
2735                 dstSwapchain->presentParms.SwapEffect = WINED3DSWAPEFFECT_COPY;
2736
2737                 TRACE("Full screen back buffer -> front buffer blt, performing a flip instead\n");
2738                 IWineD3DDevice_Present((IWineD3DDevice *) This->resource.wineD3DDevice,
2739                                         NULL, NULL, 0, NULL);
2740
2741                 dstSwapchain->presentParms.SwapEffect = orig_swap;
2742
2743                 return WINED3D_OK;
2744             }
2745             break;
2746         }
2747
2748         TRACE("Unsupported blit between buffers on the same swapchain\n");
2749         return WINED3DERR_INVALIDCALL;
2750     } else if((dstSwapchain || This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) &&
2751               (srcSwapchain || SrcSurface == myDevice->render_targets[0]) ) {
2752         ERR("Can't perform hardware blit between 2 different swapchains, falling back to software\n");
2753         return WINED3DERR_INVALIDCALL;
2754     }
2755
2756     if(srcSwapchain || SrcSurface == myDevice->render_targets[0]) {
2757         /* Blit from render target to texture */
2758         WINED3DRECT srect;
2759         BOOL upsideDown, stretchx;
2760
2761         if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
2762             TRACE("Color keying not supported by frame buffer to texture blit\n");
2763             return WINED3DERR_INVALIDCALL;
2764             /* Destination color key is checked above */
2765         }
2766
2767         /* Call preload for the surface to make sure it isn't dirty */
2768         if (GL_SUPPORT(ARB_MULTITEXTURE)) {
2769             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
2770             checkGLcall("glActiveTextureARB");
2771         }
2772         IWineD3DDeviceImpl_MarkStateDirty(This->resource.wineD3DDevice, STATE_SAMPLER(0));
2773         IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
2774
2775         /* Make sure that the top pixel is always above the bottom pixel, and keep a seperate upside down flag
2776             * glCopyTexSubImage is a bit picky about the parameters we pass to it
2777             */
2778         if(SrcRect) {
2779             if(SrcRect->top < SrcRect->bottom) {
2780                 srect.y1 = SrcRect->top;
2781                 srect.y2 = SrcRect->bottom;
2782                 upsideDown = FALSE;
2783             } else {
2784                 srect.y1 = SrcRect->bottom;
2785                 srect.y2 = SrcRect->top;
2786                 upsideDown = TRUE;
2787             }
2788             srect.x1 = SrcRect->left;
2789             srect.x2 = SrcRect->right;
2790         } else {
2791             srect.x1 = 0;
2792             srect.y1 = 0;
2793             srect.x2 = Src->currentDesc.Width;
2794             srect.y2 = Src->currentDesc.Height;
2795             upsideDown = FALSE;
2796         }
2797         if(rect.x1 > rect.x2) {
2798             UINT tmp = rect.x2;
2799             rect.x2 = rect.x1;
2800             rect.x1 = tmp;
2801             upsideDown = !upsideDown;
2802         }
2803         if(!srcSwapchain) {
2804             TRACE("Reading from an offscreen target\n");
2805             upsideDown = !upsideDown;
2806         }
2807
2808         if(rect.x2 - rect.x1 != srect.x2 - srect.x1) {
2809             stretchx = TRUE;
2810         } else {
2811             stretchx = FALSE;
2812         }
2813
2814         /* Blt is a pretty powerful call, while glCopyTexSubImage2D is not. glCopyTexSubImage cannot
2815          * flip the image nor scale it.
2816          *
2817          * -> If the app asks for a unscaled, upside down copy, just perform one glCopyTexSubImage2D call
2818          * -> If the app wants a image width an unscaled width, copy it line per line
2819          * -> If the app wants a image that is scaled on the x axis, and the destination rectangle is smaller
2820          *    than the frame buffer, draw an upside down scaled image onto the fb, read it back and restore the
2821          *    back buffer. This is slower than reading line per line, thus not used for flipping
2822          * -> If the app wants a scaled image with a dest rect that is bigger than the fb, it has to be copied
2823          *    pixel by pixel
2824          *
2825          * If EXT_framebuffer_blit is supported that can be used instead. Note that EXT_framebuffer_blit implies
2826          * FBO support, so it doesn't really make sense to try and make it work with different offscreen rendering
2827          * backends.
2828          */
2829         if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && GL_SUPPORT(EXT_FRAMEBUFFER_BLIT)) {
2830             stretch_rect_fbo((IWineD3DDevice *)myDevice, SrcSurface, &srect,
2831                     (IWineD3DSurface *)This, &rect, Filter, upsideDown);
2832         } else if((!stretchx) || rect.x2 - rect.x1 > Src->currentDesc.Width ||
2833                                     rect.y2 - rect.y1 > Src->currentDesc.Height) {
2834             TRACE("No stretching in x direction, using direct framebuffer -> texture copy\n");
2835             fb_copy_to_texture_direct(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
2836         } else {
2837             TRACE("Using hardware stretching to flip / stretch the texture\n");
2838             fb_copy_to_texture_hwstretch(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
2839         }
2840
2841         if(!(This->Flags & SFLAG_DONOTFREE)) {
2842             HeapFree(GetProcessHeap(), 0, This->resource.allocatedMemory);
2843             This->resource.allocatedMemory = NULL;
2844         } else {
2845             This->Flags &= ~SFLAG_INSYSMEM;
2846         }
2847         /* The texture is now most up to date - If the surface is a render target and has a drawable, this
2848          * path is never entered
2849          */
2850         This->Flags |= SFLAG_INTEXTURE;
2851
2852         return WINED3D_OK;
2853     } else if(Src) {
2854         /* Blit from offscreen surface to render target */
2855         float glTexCoord[4];
2856         DWORD oldCKeyFlags = Src->CKeyFlags;
2857         WINEDDCOLORKEY oldBltCKey = This->SrcBltCKey;
2858         RECT SourceRectangle;
2859
2860         TRACE("Blt from surface %p to rendertarget %p\n", Src, This);
2861
2862         if(SrcRect) {
2863             SourceRectangle.left = SrcRect->left;
2864             SourceRectangle.right = SrcRect->right;
2865             SourceRectangle.top = SrcRect->top;
2866             SourceRectangle.bottom = SrcRect->bottom;
2867         } else {
2868             SourceRectangle.left = 0;
2869             SourceRectangle.right = Src->currentDesc.Width;
2870             SourceRectangle.top = 0;
2871             SourceRectangle.bottom = Src->currentDesc.Height;
2872         }
2873
2874         if(!CalculateTexRect(Src, &SourceRectangle, glTexCoord)) {
2875             /* Fall back to software */
2876             WARN("(%p) Source texture area (%d,%d)-(%d,%d) is too big\n", Src,
2877                     SourceRectangle.left, SourceRectangle.top,
2878                     SourceRectangle.right, SourceRectangle.bottom);
2879             return WINED3DERR_INVALIDCALL;
2880         }
2881
2882         /* Color keying: Check if we have to do a color keyed blt,
2883          * and if not check if a color key is activated.
2884          *
2885          * Just modify the color keying parameters in the surface and restore them afterwards
2886          * The surface keeps track of the color key last used to load the opengl surface.
2887          * PreLoad will catch the change to the flags and color key and reload if neccessary.
2888          */
2889         if(Flags & WINEDDBLT_KEYSRC) {
2890             /* Use color key from surface */
2891         } else if(Flags & WINEDDBLT_KEYSRCOVERRIDE) {
2892             /* Use color key from DDBltFx */
2893             Src->CKeyFlags |= WINEDDSD_CKSRCBLT;
2894             This->SrcBltCKey = DDBltFx->ddckSrcColorkey;
2895         } else {
2896             /* Do not use color key */
2897             Src->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
2898         }
2899
2900         /* Now load the surface */
2901         IWineD3DSurface_PreLoad((IWineD3DSurface *) Src);
2902
2903         ENTER_GL();
2904
2905         /* Activate the destination context, set it up for blitting */
2906         ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
2907
2908         if(!dstSwapchain) {
2909             TRACE("Drawing to offscreen buffer\n");
2910             glDrawBuffer(myDevice->offscreenBuffer);
2911         } else {
2912             GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *)This, (IWineD3DSwapChain *)dstSwapchain);
2913             TRACE("Drawing to %#x buffer\n", buffer);
2914             glDrawBuffer(buffer);
2915             checkGLcall("glDrawBuffer");
2916         }
2917
2918         /* Bind the texture */
2919         glBindTexture(GL_TEXTURE_2D, Src->glDescription.textureName);
2920         checkGLcall("glBindTexture");
2921
2922         /* Filtering for StretchRect */
2923         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
2924                         stateLookup[WINELOOKUP_MAGFILTER][Filter - minLookup[WINELOOKUP_MAGFILTER]]);
2925         checkGLcall("glTexParameteri");
2926         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
2927                         minMipLookup[Filter][WINED3DTEXF_NONE]);
2928         checkGLcall("glTexParameteri");
2929         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
2930         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
2931         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2932         checkGLcall("glTexEnvi");
2933
2934         /* This is for color keying */
2935         if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
2936             glEnable(GL_ALPHA_TEST);
2937             checkGLcall("glEnable GL_ALPHA_TEST");
2938             glAlphaFunc(GL_NOTEQUAL, 0.0);
2939             checkGLcall("glAlphaFunc\n");
2940         } else {
2941             glDisable(GL_ALPHA_TEST);
2942             checkGLcall("glDisable GL_ALPHA_TEST");
2943         }
2944
2945         /* Draw a textured quad
2946          */
2947         glBegin(GL_QUADS);
2948
2949         glColor3d(1.0f, 1.0f, 1.0f);
2950         glTexCoord2f(glTexCoord[0], glTexCoord[2]);
2951         glVertex3f(rect.x1,
2952                     rect.y1,
2953                     0.0);
2954
2955         glTexCoord2f(glTexCoord[0], glTexCoord[3]);
2956         glVertex3f(rect.x1, rect.y2, 0.0);
2957
2958         glTexCoord2f(glTexCoord[1], glTexCoord[3]);
2959         glVertex3f(rect.x2,
2960                     rect.y2,
2961                     0.0);
2962
2963         glTexCoord2f(glTexCoord[1], glTexCoord[2]);
2964         glVertex3f(rect.x2,
2965                     rect.y1,
2966                     0.0);
2967         glEnd();
2968         checkGLcall("glEnd");
2969
2970         if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
2971             glDisable(GL_ALPHA_TEST);
2972             checkGLcall("glDisable(GL_ALPHA_TEST)");
2973         }
2974
2975         /* Unbind the texture */
2976         glBindTexture(GL_TEXTURE_2D, 0);
2977         checkGLcall("glEnable glBindTexture");
2978
2979         /* The draw buffer should only need to be restored if we were drawing to the front buffer, and there is a back buffer.
2980          * otherwise the context manager should choose between GL_BACK / offscreenDrawBuffer
2981          */
2982         if(dstSwapchain && This == (IWineD3DSurfaceImpl *) dstSwapchain->frontBuffer && dstSwapchain->backBuffer) {
2983             glDrawBuffer(GL_BACK);
2984         }
2985         /* Restore the color key parameters */
2986         Src->CKeyFlags = oldCKeyFlags;
2987         This->SrcBltCKey = oldBltCKey;
2988
2989         LEAVE_GL();
2990
2991         /* TODO: If the surface is locked often, perform the Blt in software on the memory instead */
2992         This->Flags &= ~SFLAG_INSYSMEM;
2993         /* The surface is now in the drawable. On onscreen surfaces or without fbos the texture
2994          * is outdated now
2995          */
2996         if(dstSwapchain || wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
2997             This->Flags |= SFLAG_INDRAWABLE;
2998             This->Flags &= ~SFLAG_INTEXTURE;
2999         } else {
3000             This->Flags |= SFLAG_INTEXTURE;
3001         }
3002
3003         return WINED3D_OK;
3004     } else {
3005         /* Source-Less Blit to render target */
3006         if (Flags & WINEDDBLT_COLORFILL) {
3007             /* This is easy to handle for the D3D Device... */
3008             DWORD color;
3009
3010             TRACE("Colorfill\n");
3011
3012             /* The color as given in the Blt function is in the format of the frame-buffer...
3013              * 'clear' expect it in ARGB format => we need to do some conversion :-)
3014              */
3015             if (This->resource.format == WINED3DFMT_P8) {
3016                 if (This->palette) {
3017                     color = ((0xFF000000) |
3018                             (This->palette->palents[DDBltFx->u5.dwFillColor].peRed << 16) |
3019                             (This->palette->palents[DDBltFx->u5.dwFillColor].peGreen << 8) |
3020                             (This->palette->palents[DDBltFx->u5.dwFillColor].peBlue));
3021                 } else {
3022                     color = 0xFF000000;
3023                 }
3024             }
3025             else if (This->resource.format == WINED3DFMT_R5G6B5) {
3026                 if (DDBltFx->u5.dwFillColor == 0xFFFF) {
3027                     color = 0xFFFFFFFF;
3028                 } else {
3029                     color = ((0xFF000000) |
3030                             ((DDBltFx->u5.dwFillColor & 0xF800) << 8) |
3031                             ((DDBltFx->u5.dwFillColor & 0x07E0) << 5) |
3032                             ((DDBltFx->u5.dwFillColor & 0x001F) << 3));
3033                 }
3034             }
3035             else if ((This->resource.format == WINED3DFMT_R8G8B8) ||
3036                     (This->resource.format == WINED3DFMT_X8R8G8B8) ) {
3037                 color = 0xFF000000 | DDBltFx->u5.dwFillColor;
3038             }
3039             else if (This->resource.format == WINED3DFMT_A8R8G8B8) {
3040                 color = DDBltFx->u5.dwFillColor;
3041             }
3042             else {
3043                 ERR("Wrong surface type for BLT override(Format doesn't match) !\n");
3044                 return WINED3DERR_INVALIDCALL;
3045             }
3046
3047             TRACE("Calling GetSwapChain with mydevice = %p\n", myDevice);
3048             if(dstSwapchain && dstSwapchain->backBuffer && This == (IWineD3DSurfaceImpl*) dstSwapchain->backBuffer[0]) {
3049                 glDrawBuffer(GL_BACK);
3050                 checkGLcall("glDrawBuffer(GL_BACK)");
3051             } else if (dstSwapchain && This == (IWineD3DSurfaceImpl*) dstSwapchain->frontBuffer) {
3052                 glDrawBuffer(GL_FRONT);
3053                 checkGLcall("glDrawBuffer(GL_FRONT)");
3054             } else if(This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
3055                 glDrawBuffer(myDevice->offscreenBuffer);
3056                 checkGLcall("glDrawBuffer(myDevice->offscreenBuffer3)");
3057             } else {
3058                 TRACE("Surface is higher back buffer, falling back to software\n");
3059                 return WINED3DERR_INVALIDCALL;
3060             }
3061
3062             TRACE("(%p) executing Render Target override, color = %x\n", This, color);
3063
3064             IWineD3DDevice_Clear( (IWineD3DDevice *) myDevice,
3065                                 1 /* Number of rectangles */,
3066                                 &rect,
3067                                 WINED3DCLEAR_TARGET,
3068                                 color,
3069                                 0.0 /* Z */,
3070                                 0 /* Stencil */);
3071
3072             /* Restore the original draw buffer */
3073             if(!dstSwapchain) {
3074                 glDrawBuffer(myDevice->offscreenBuffer);
3075             } else if(dstSwapchain->backBuffer && dstSwapchain->backBuffer[0]) {
3076                 glDrawBuffer(GL_BACK);
3077             }
3078             vcheckGLcall("glDrawBuffer");
3079
3080             return WINED3D_OK;
3081         }
3082     }
3083
3084     /* Default: Fall back to the generic blt. Not an error, a TRACE is enough */
3085     TRACE("Didn't find any usable render target setup for hw blit, falling back to software\n");
3086     return WINED3DERR_INVALIDCALL;
3087 }
3088
3089 static HRESULT WINAPI IWineD3DSurfaceImpl_Blt(IWineD3DSurface *iface, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
3090     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3091     IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
3092     IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3093     TRACE("(%p)->(%p,%p,%p,%x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3094     TRACE("(%p): Usage is %s\n", This, debug_d3dusage(This->resource.usage));
3095
3096     /* Accessing the depth stencil is supposed to fail between a BeginScene and EndScene pair */
3097     if(myDevice->inScene &&
3098        (iface == myDevice->stencilBufferTarget ||
3099        (SrcSurface && SrcSurface == myDevice->stencilBufferTarget))) {
3100         TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3101         return WINED3DERR_INVALIDCALL;
3102     }
3103
3104     /* Special cases for RenderTargets */
3105     if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3106         ( Src && (Src->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3107         if(IWineD3DSurfaceImpl_BltOverride(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter) == WINED3D_OK) return WINED3D_OK;
3108     }
3109
3110     /* For the rest call the X11 surface implementation.
3111      * For RenderTargets this should be implemented OpenGL accelerated in BltOverride,
3112      * other Blts are rather rare
3113      */
3114     return IWineGDISurfaceImpl_Blt(iface, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter);
3115 }
3116
3117 HRESULT WINAPI IWineD3DSurfaceImpl_GetBltStatus(IWineD3DSurface *iface, DWORD Flags) {
3118     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3119     TRACE("(%p)->(%x)\n", This, Flags);
3120
3121     switch (Flags)
3122     {
3123     case WINEDDGBS_CANBLT:
3124     case WINEDDGBS_ISBLTDONE:
3125         return WINED3D_OK;
3126
3127     default:
3128         return WINED3DERR_INVALIDCALL;
3129     }
3130 }
3131
3132 HRESULT WINAPI IWineD3DSurfaceImpl_GetFlipStatus(IWineD3DSurface *iface, DWORD Flags) {
3133     /* XXX: DDERR_INVALIDSURFACETYPE */
3134
3135     TRACE("(%p)->(%08x)\n",iface,Flags);
3136     switch (Flags) {
3137     case WINEDDGFS_CANFLIP:
3138     case WINEDDGFS_ISFLIPDONE:
3139         return WINED3D_OK;
3140
3141     default:
3142         return WINED3DERR_INVALIDCALL;
3143     }
3144 }
3145
3146 HRESULT WINAPI IWineD3DSurfaceImpl_IsLost(IWineD3DSurface *iface) {
3147     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3148     TRACE("(%p)\n", This);
3149
3150     /* D3D8 and 9 loose full devices, ddraw only surfaces */
3151     return This->Flags & SFLAG_LOST ? WINED3DERR_DEVICELOST : WINED3D_OK;
3152 }
3153
3154 HRESULT WINAPI IWineD3DSurfaceImpl_Restore(IWineD3DSurface *iface) {
3155     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3156     TRACE("(%p)\n", This);
3157
3158     /* So far we don't lose anything :) */
3159     This->Flags &= ~SFLAG_LOST;
3160     return WINED3D_OK;
3161 }
3162
3163 HRESULT WINAPI IWineD3DSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty, IWineD3DSurface *Source, RECT *rsrc, DWORD trans) {
3164     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3165     IWineD3DSurfaceImpl *srcImpl = (IWineD3DSurfaceImpl *) Source;
3166     IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3167     TRACE("(%p)->(%d, %d, %p, %p, %08x\n", iface, dstx, dsty, Source, rsrc, trans);
3168
3169     if(myDevice->inScene &&
3170        (iface == myDevice->stencilBufferTarget ||
3171        (Source && Source == myDevice->stencilBufferTarget))) {
3172         TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3173         return WINED3DERR_INVALIDCALL;
3174     }
3175
3176     /* Special cases for RenderTargets */
3177     if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3178         ( srcImpl && (srcImpl->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3179
3180         RECT SrcRect, DstRect;
3181         DWORD Flags=0;
3182
3183         if(rsrc) {
3184             SrcRect.left = rsrc->left;
3185             SrcRect.top= rsrc->top;
3186             SrcRect.bottom = rsrc->bottom;
3187             SrcRect.right = rsrc->right;
3188         } else {
3189             SrcRect.left = 0;
3190             SrcRect.top = 0;
3191             SrcRect.right = srcImpl->currentDesc.Width;
3192             SrcRect.bottom = srcImpl->currentDesc.Height;
3193         }
3194
3195         DstRect.left = dstx;
3196         DstRect.top=dsty;
3197         DstRect.right = dstx + SrcRect.right - SrcRect.left;
3198         DstRect.bottom = dsty + SrcRect.bottom - SrcRect.top;
3199
3200         /* Convert BltFast flags into Btl ones because it is called from SurfaceImpl_Blt as well */
3201         if(trans & WINEDDBLTFAST_SRCCOLORKEY)
3202             Flags |= WINEDDBLT_KEYSRC;
3203         if(trans & WINEDDBLTFAST_DESTCOLORKEY)
3204             Flags |= WINEDDBLT_KEYDEST;
3205         if(trans & WINEDDBLTFAST_WAIT)
3206             Flags |= WINEDDBLT_WAIT;
3207         if(trans & WINEDDBLTFAST_DONOTWAIT)
3208             Flags |= WINEDDBLT_DONOTWAIT;
3209
3210         if(IWineD3DSurfaceImpl_BltOverride(This, &DstRect, Source, &SrcRect, Flags, NULL, WINED3DTEXF_NONE) == WINED3D_OK) return WINED3D_OK;
3211     }
3212
3213
3214     return IWineGDISurfaceImpl_BltFast(iface, dstx, dsty, Source, rsrc, trans);
3215 }
3216
3217 HRESULT WINAPI IWineD3DSurfaceImpl_GetPalette(IWineD3DSurface *iface, IWineD3DPalette **Pal) {
3218     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3219     TRACE("(%p)->(%p)\n", This, Pal);
3220
3221     *Pal = (IWineD3DPalette *) This->palette;
3222     return WINED3D_OK;
3223 }
3224
3225 HRESULT WINAPI IWineD3DSurfaceImpl_RealizePalette(IWineD3DSurface *iface) {
3226     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3227     RGBQUAD col[256];
3228     IWineD3DPaletteImpl *pal = This->palette;
3229     unsigned int n;
3230     TRACE("(%p)\n", This);
3231
3232     if(This->resource.format == WINED3DFMT_P8 ||
3233        This->resource.format == WINED3DFMT_A8P8)
3234     {
3235         if(!This->Flags & SFLAG_INSYSMEM) {
3236             FIXME("Palette changed with surface that does not have an up to date system memory copy\n");
3237         }
3238         TRACE("Dirtifying surface\n");
3239         This->Flags &= ~(SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
3240     }
3241
3242     if(This->Flags & SFLAG_DIBSECTION) {
3243         TRACE("(%p): Updating the hdc's palette\n", This);
3244         for (n=0; n<256; n++) {
3245             if(pal) {
3246                 col[n].rgbRed   = pal->palents[n].peRed;
3247                 col[n].rgbGreen = pal->palents[n].peGreen;
3248                 col[n].rgbBlue  = pal->palents[n].peBlue;
3249             } else {
3250                 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
3251                 /* Use the default device palette */
3252                 col[n].rgbRed   = device->palettes[device->currentPalette][n].peRed;
3253                 col[n].rgbGreen = device->palettes[device->currentPalette][n].peGreen;
3254                 col[n].rgbBlue  = device->palettes[device->currentPalette][n].peBlue;
3255             }
3256             col[n].rgbReserved = 0;
3257         }
3258         SetDIBColorTable(This->hDC, 0, 256, col);
3259     }
3260
3261     return WINED3D_OK;
3262 }
3263
3264 HRESULT WINAPI IWineD3DSurfaceImpl_SetPalette(IWineD3DSurface *iface, IWineD3DPalette *Pal) {
3265     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3266     IWineD3DPaletteImpl *PalImpl = (IWineD3DPaletteImpl *) Pal;
3267     TRACE("(%p)->(%p)\n", This, Pal);
3268
3269     if(This->palette != NULL) 
3270         if(This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3271             This->palette->Flags &= ~WINEDDPCAPS_PRIMARYSURFACE;
3272
3273     if(PalImpl != NULL) {
3274         if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
3275             /* Set the device's main palette if the palette
3276              * wasn't a primary palette before
3277              */
3278             if(!(PalImpl->Flags & WINEDDPCAPS_PRIMARYSURFACE)) {
3279                 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
3280                 unsigned int i;
3281
3282                 for(i=0; i < 256; i++) {
3283                     device->palettes[device->currentPalette][i] = PalImpl->palents[i];
3284                 }
3285             }
3286
3287             (PalImpl)->Flags |= WINEDDPCAPS_PRIMARYSURFACE;
3288         }
3289     }
3290     This->palette = PalImpl;
3291
3292     return IWineD3DSurface_RealizePalette(iface);
3293 }
3294
3295 HRESULT WINAPI IWineD3DSurfaceImpl_SetColorKey(IWineD3DSurface *iface, DWORD Flags, WINEDDCOLORKEY *CKey) {
3296     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3297     TRACE("(%p)->(%08x,%p)\n", This, Flags, CKey);
3298
3299     if ((Flags & WINEDDCKEY_COLORSPACE) != 0) {
3300         FIXME(" colorkey value not supported (%08x) !\n", Flags);
3301         return WINED3DERR_INVALIDCALL;
3302     }
3303
3304     /* Dirtify the surface, but only if a key was changed */
3305     if(CKey) {
3306         switch (Flags & ~WINEDDCKEY_COLORSPACE) {
3307             case WINEDDCKEY_DESTBLT:
3308                 This->DestBltCKey = *CKey;
3309                 This->CKeyFlags |= WINEDDSD_CKDESTBLT;
3310                 break;
3311
3312             case WINEDDCKEY_DESTOVERLAY:
3313                 This->DestOverlayCKey = *CKey;
3314                 This->CKeyFlags |= WINEDDSD_CKDESTOVERLAY;
3315                 break;
3316
3317             case WINEDDCKEY_SRCOVERLAY:
3318                 This->SrcOverlayCKey = *CKey;
3319                 This->CKeyFlags |= WINEDDSD_CKSRCOVERLAY;
3320                 break;
3321
3322             case WINEDDCKEY_SRCBLT:
3323                 This->SrcBltCKey = *CKey;
3324                 This->CKeyFlags |= WINEDDSD_CKSRCBLT;
3325                 break;
3326         }
3327     }
3328     else {
3329         switch (Flags & ~WINEDDCKEY_COLORSPACE) {
3330             case WINEDDCKEY_DESTBLT:
3331                 This->CKeyFlags &= ~WINEDDSD_CKDESTBLT;
3332                 break;
3333
3334             case WINEDDCKEY_DESTOVERLAY:
3335                 This->CKeyFlags &= ~WINEDDSD_CKDESTOVERLAY;
3336                 break;
3337
3338             case WINEDDCKEY_SRCOVERLAY:
3339                 This->CKeyFlags &= ~WINEDDSD_CKSRCOVERLAY;
3340                 break;
3341
3342             case WINEDDCKEY_SRCBLT:
3343                 This->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
3344                 break;
3345         }
3346     }
3347
3348     return WINED3D_OK;
3349 }
3350
3351 static HRESULT WINAPI IWineD3DSurfaceImpl_PrivateSetup(IWineD3DSurface *iface) {
3352     /** Check against the maximum texture sizes supported by the video card **/
3353     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3354
3355     TRACE("%p\n", This);
3356     if ((This->pow2Width > GL_LIMITS(texture_size) || This->pow2Height > GL_LIMITS(texture_size)) && !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL))) {
3357         /* one of three options
3358         1: Do the same as we do with nonpow 2 and scale the texture, (any texture ops would require the texture to be scaled which is potentially slow)
3359         2: Set the texture to the maxium size (bad idea)
3360         3:    WARN and return WINED3DERR_NOTAVAILABLE;
3361         4: Create the surface, but allow it to be used only for DirectDraw Blts. Some apps(e.g. Swat 3) create textures with a Height of 16 and a Width > 3000 and blt 16x16 letter areas from them to the render target.
3362         */
3363         WARN("(%p) Creating an oversized surface\n", This);
3364         This->Flags |= SFLAG_OVERSIZE;
3365
3366         /* This will be initialized on the first blt */
3367         This->glRect.left = 0;
3368         This->glRect.top = 0;
3369         This->glRect.right = 0;
3370         This->glRect.bottom = 0;
3371     } else {
3372         /* No oversize, gl rect is the full texture size */
3373         This->Flags &= ~SFLAG_OVERSIZE;
3374         This->glRect.left = 0;
3375         This->glRect.top = 0;
3376         This->glRect.right = This->pow2Width;
3377         This->glRect.bottom = This->pow2Height;
3378     }
3379
3380     if(GL_SUPPORT(APPLE_CLIENT_STORAGE) && This->resource.allocatedMemory == NULL) {
3381         /* Make sure that memory is allocated from the start if we are going to use GL_APPLE_client_storage.
3382          * Otherwise a glTexImage2D with a NULL pointer may be done, e.g. when blitting or with offscreen render
3383          * targets, thus the client storage wouldn't be used for that texture
3384          */
3385         This->resource.allocatedMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, This->resource.size + 4);
3386     }
3387     return WINED3D_OK;
3388 }
3389
3390 DWORD WINAPI IWineD3DSurfaceImpl_GetPitch(IWineD3DSurface *iface) {
3391     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3392     DWORD ret;
3393     TRACE("(%p)\n", This);
3394
3395     /* DXTn formats don't have exact pitches as they are to the new row of blocks,
3396          where each block is 4x4 pixels, 8 bytes (dxt1) and 16 bytes (dxt2/3/4/5)
3397           ie pitch = (width/4) * bytes per block                                  */
3398     if (This->resource.format == WINED3DFMT_DXT1) /* DXT1 is 8 bytes per block */
3399         ret = ((This->currentDesc.Width + 3) >> 2) << 3;
3400     else if (This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
3401              This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) /* DXT2/3/4/5 is 16 bytes per block */
3402         ret = ((This->currentDesc.Width + 3) >> 2) << 4;
3403     else {
3404         ret = This->bytesPerPixel * This->currentDesc.Width;  /* Bytes / row */
3405         /* Surfaces are 32 bit aligned */
3406         ret = (ret + SURFACE_ALIGNMENT - 1) & ~(SURFACE_ALIGNMENT - 1);
3407     }
3408     TRACE("(%p) Returning %d\n", This, ret);
3409     return ret;
3410 }
3411
3412 HRESULT WINAPI IWineD3DSurfaceImpl_SetOverlayPosition(IWineD3DSurface *iface, LONG X, LONG Y) {
3413     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3414
3415     FIXME("(%p)->(%d,%d) Stub!\n", This, X, Y);
3416
3417     if(!(This->resource.usage & WINED3DUSAGE_OVERLAY))
3418     {
3419         TRACE("(%p): Not an overlay surface\n", This);
3420         return WINEDDERR_NOTAOVERLAYSURFACE;
3421     }
3422
3423     return WINED3D_OK;
3424 }
3425
3426 HRESULT WINAPI IWineD3DSurfaceImpl_GetOverlayPosition(IWineD3DSurface *iface, LONG *X, LONG *Y) {
3427     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3428
3429     FIXME("(%p)->(%p,%p) Stub!\n", This, X, Y);
3430
3431     if(!(This->resource.usage & WINED3DUSAGE_OVERLAY))
3432     {
3433         TRACE("(%p): Not an overlay surface\n", This);
3434         return WINEDDERR_NOTAOVERLAYSURFACE;
3435     }
3436
3437     return WINED3D_OK;
3438 }
3439
3440 HRESULT WINAPI IWineD3DSurfaceImpl_UpdateOverlayZOrder(IWineD3DSurface *iface, DWORD Flags, IWineD3DSurface *Ref) {
3441     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3442     IWineD3DSurfaceImpl *RefImpl = (IWineD3DSurfaceImpl *) Ref;
3443
3444     FIXME("(%p)->(%08x,%p) Stub!\n", This, Flags, RefImpl);
3445
3446     if(!(This->resource.usage & WINED3DUSAGE_OVERLAY))
3447     {
3448         TRACE("(%p): Not an overlay surface\n", This);
3449         return WINEDDERR_NOTAOVERLAYSURFACE;
3450     }
3451
3452     return WINED3D_OK;
3453 }
3454
3455 HRESULT WINAPI IWineD3DSurfaceImpl_UpdateOverlay(IWineD3DSurface *iface, RECT *SrcRect, IWineD3DSurface *DstSurface, RECT *DstRect, DWORD Flags, WINEDDOVERLAYFX *FX) {
3456     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3457     IWineD3DSurfaceImpl *Dst = (IWineD3DSurfaceImpl *) DstSurface;
3458     FIXME("(%p)->(%p, %p, %p, %08x, %p)\n", This, SrcRect, Dst, DstRect, Flags, FX);
3459
3460     if(!(This->resource.usage & WINED3DUSAGE_OVERLAY))
3461     {
3462         TRACE("(%p): Not an overlay surface\n", This);
3463         return WINEDDERR_NOTAOVERLAYSURFACE;
3464     }
3465
3466     return WINED3D_OK;
3467 }
3468
3469 HRESULT WINAPI IWineD3DSurfaceImpl_SetClipper(IWineD3DSurface *iface, IWineD3DClipper *clipper)
3470 {
3471     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3472     TRACE("(%p)->(%p)\n", This, clipper);
3473
3474     This->clipper = clipper;
3475     return WINED3D_OK;
3476 }
3477
3478 HRESULT WINAPI IWineD3DSurfaceImpl_GetClipper(IWineD3DSurface *iface, IWineD3DClipper **clipper)
3479 {
3480     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3481     TRACE("(%p)->(%p)\n", This, clipper);
3482
3483     *clipper = This->clipper;
3484     IWineD3DClipper_AddRef(*clipper);
3485     return WINED3D_OK;
3486 }
3487
3488 const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl =
3489 {
3490     /* IUnknown */
3491     IWineD3DSurfaceImpl_QueryInterface,
3492     IWineD3DSurfaceImpl_AddRef,
3493     IWineD3DSurfaceImpl_Release,
3494     /* IWineD3DResource */
3495     IWineD3DSurfaceImpl_GetParent,
3496     IWineD3DSurfaceImpl_GetDevice,
3497     IWineD3DSurfaceImpl_SetPrivateData,
3498     IWineD3DSurfaceImpl_GetPrivateData,
3499     IWineD3DSurfaceImpl_FreePrivateData,
3500     IWineD3DSurfaceImpl_SetPriority,
3501     IWineD3DSurfaceImpl_GetPriority,
3502     IWineD3DSurfaceImpl_PreLoad,
3503     IWineD3DSurfaceImpl_GetType,
3504     /* IWineD3DSurface */
3505     IWineD3DSurfaceImpl_GetContainer,
3506     IWineD3DSurfaceImpl_GetDesc,
3507     IWineD3DSurfaceImpl_LockRect,
3508     IWineD3DSurfaceImpl_UnlockRect,
3509     IWineD3DSurfaceImpl_GetDC,
3510     IWineD3DSurfaceImpl_ReleaseDC,
3511     IWineD3DSurfaceImpl_Flip,
3512     IWineD3DSurfaceImpl_Blt,
3513     IWineD3DSurfaceImpl_GetBltStatus,
3514     IWineD3DSurfaceImpl_GetFlipStatus,
3515     IWineD3DSurfaceImpl_IsLost,
3516     IWineD3DSurfaceImpl_Restore,
3517     IWineD3DSurfaceImpl_BltFast,
3518     IWineD3DSurfaceImpl_GetPalette,
3519     IWineD3DSurfaceImpl_SetPalette,
3520     IWineD3DSurfaceImpl_RealizePalette,
3521     IWineD3DSurfaceImpl_SetColorKey,
3522     IWineD3DSurfaceImpl_GetPitch,
3523     IWineD3DSurfaceImpl_SetMem,
3524     IWineD3DSurfaceImpl_SetOverlayPosition,
3525     IWineD3DSurfaceImpl_GetOverlayPosition,
3526     IWineD3DSurfaceImpl_UpdateOverlayZOrder,
3527     IWineD3DSurfaceImpl_UpdateOverlay,
3528     IWineD3DSurfaceImpl_SetClipper,
3529     IWineD3DSurfaceImpl_GetClipper,
3530     /* Internal use: */
3531     IWineD3DSurfaceImpl_AddDirtyRect,
3532     IWineD3DSurfaceImpl_LoadTexture,
3533     IWineD3DSurfaceImpl_SaveSnapshot,
3534     IWineD3DSurfaceImpl_SetContainer,
3535     IWineD3DSurfaceImpl_SetGlTextureDesc,
3536     IWineD3DSurfaceImpl_GetGlDesc,
3537     IWineD3DSurfaceImpl_GetData,
3538     IWineD3DSurfaceImpl_SetFormat,
3539     IWineD3DSurfaceImpl_PrivateSetup
3540 };