wined3d: Allow FBO blits again between surfaces with fixups if they have the same...
[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-2008 Stefan Dösinger for CodeWeavers
11  * Copyright 2007-2008 Henri Verbeet
12  * Copyright 2006-2008 Roderick Colenbrander
13  * Copyright 2009 Henri Verbeet for CodeWeavers
14  *
15  * This library is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Lesser General Public
17  * License as published by the Free Software Foundation; either
18  * version 2.1 of the License, or (at your option) any later version.
19  *
20  * This library is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public
26  * License along with this library; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
28  */
29
30 #include "config.h"
31 #include "wine/port.h"
32 #include "wined3d_private.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(d3d_surface);
35 WINE_DECLARE_DEBUG_CHANNEL(d3d);
36
37 static void surface_cleanup(IWineD3DSurfaceImpl *This)
38 {
39     TRACE("(%p) : Cleaning up.\n", This);
40
41     if (This->texture_name || (This->Flags & SFLAG_PBO) || !list_empty(&This->renderbuffers))
42     {
43         const struct wined3d_gl_info *gl_info;
44         renderbuffer_entry_t *entry, *entry2;
45         struct wined3d_context *context;
46
47         context = context_acquire(This->resource.device, NULL);
48         gl_info = context->gl_info;
49
50         ENTER_GL();
51
52         if (This->texture_name)
53         {
54             TRACE("Deleting texture %u.\n", This->texture_name);
55             glDeleteTextures(1, &This->texture_name);
56         }
57
58         if (This->Flags & SFLAG_PBO)
59         {
60             TRACE("Deleting PBO %u.\n", This->pbo);
61             GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
62         }
63
64         LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry)
65         {
66             TRACE("Deleting renderbuffer %u.\n", entry->id);
67             gl_info->fbo_ops.glDeleteRenderbuffers(1, &entry->id);
68             HeapFree(GetProcessHeap(), 0, entry);
69         }
70
71         LEAVE_GL();
72
73         context_release(context);
74     }
75
76     if (This->Flags & SFLAG_DIBSECTION)
77     {
78         /* Release the DC. */
79         SelectObject(This->hDC, This->dib.holdbitmap);
80         DeleteDC(This->hDC);
81         /* Release the DIB section. */
82         DeleteObject(This->dib.DIBsection);
83         This->dib.bitmap_data = NULL;
84         This->resource.allocatedMemory = NULL;
85     }
86
87     if (This->Flags & SFLAG_USERPTR) IWineD3DSurface_SetMem((IWineD3DSurface *)This, NULL);
88     if (This->overlay_dest) list_remove(&This->overlay_entry);
89
90     HeapFree(GetProcessHeap(), 0, This->palette9);
91
92     resource_cleanup((IWineD3DResource *)This);
93 }
94
95 void surface_set_container(IWineD3DSurfaceImpl *surface, enum wined3d_container_type type, IWineD3DBase *container)
96 {
97     TRACE("surface %p, container %p.\n", surface, container);
98
99     if (!container && type != WINED3D_CONTAINER_NONE)
100         ERR("Setting NULL container of type %#x.\n", type);
101
102     if (type == WINED3D_CONTAINER_SWAPCHAIN)
103     {
104         surface->get_drawable_size = get_drawable_size_swapchain;
105     }
106     else
107     {
108         switch (wined3d_settings.offscreen_rendering_mode)
109         {
110             case ORM_FBO:
111                 surface->get_drawable_size = get_drawable_size_fbo;
112                 break;
113
114             case ORM_BACKBUFFER:
115                 surface->get_drawable_size = get_drawable_size_backbuffer;
116                 break;
117
118             default:
119                 ERR("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
120                 return;
121         }
122     }
123
124     surface->container.type = type;
125     surface->container.u.base = container;
126 }
127
128 struct blt_info
129 {
130     GLenum binding;
131     GLenum bind_target;
132     enum tex_types tex_type;
133     GLfloat coords[4][3];
134 };
135
136 struct float_rect
137 {
138     float l;
139     float t;
140     float r;
141     float b;
142 };
143
144 static inline void cube_coords_float(const RECT *r, UINT w, UINT h, struct float_rect *f)
145 {
146     f->l = ((r->left * 2.0f) / w) - 1.0f;
147     f->t = ((r->top * 2.0f) / h) - 1.0f;
148     f->r = ((r->right * 2.0f) / w) - 1.0f;
149     f->b = ((r->bottom * 2.0f) / h) - 1.0f;
150 }
151
152 static void surface_get_blt_info(GLenum target, const RECT *rect_in, GLsizei w, GLsizei h, struct blt_info *info)
153 {
154     GLfloat (*coords)[3] = info->coords;
155     RECT rect;
156     struct float_rect f;
157
158     if (rect_in)
159         rect = *rect_in;
160     else
161     {
162         rect.left = 0;
163         rect.top = h;
164         rect.right = w;
165         rect.bottom = 0;
166     }
167
168     switch (target)
169     {
170         default:
171             FIXME("Unsupported texture target %#x\n", target);
172             /* Fall back to GL_TEXTURE_2D */
173         case GL_TEXTURE_2D:
174             info->binding = GL_TEXTURE_BINDING_2D;
175             info->bind_target = GL_TEXTURE_2D;
176             info->tex_type = tex_2d;
177             coords[0][0] = (float)rect.left / w;
178             coords[0][1] = (float)rect.top / h;
179             coords[0][2] = 0.0f;
180
181             coords[1][0] = (float)rect.right / w;
182             coords[1][1] = (float)rect.top / h;
183             coords[1][2] = 0.0f;
184
185             coords[2][0] = (float)rect.left / w;
186             coords[2][1] = (float)rect.bottom / h;
187             coords[2][2] = 0.0f;
188
189             coords[3][0] = (float)rect.right / w;
190             coords[3][1] = (float)rect.bottom / h;
191             coords[3][2] = 0.0f;
192             break;
193
194         case GL_TEXTURE_RECTANGLE_ARB:
195             info->binding = GL_TEXTURE_BINDING_RECTANGLE_ARB;
196             info->bind_target = GL_TEXTURE_RECTANGLE_ARB;
197             info->tex_type = tex_rect;
198             coords[0][0] = rect.left;   coords[0][1] = rect.top;     coords[0][2] = 0.0f;
199             coords[1][0] = rect.right;  coords[1][1] = rect.top;     coords[1][2] = 0.0f;
200             coords[2][0] = rect.left;   coords[2][1] = rect.bottom;  coords[2][2] = 0.0f;
201             coords[3][0] = rect.right;  coords[3][1] = rect.bottom;  coords[3][2] = 0.0f;
202             break;
203
204         case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
205             info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
206             info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
207             info->tex_type = tex_cube;
208             cube_coords_float(&rect, w, h, &f);
209
210             coords[0][0] =  1.0f;   coords[0][1] = -f.t;   coords[0][2] = -f.l;
211             coords[1][0] =  1.0f;   coords[1][1] = -f.t;   coords[1][2] = -f.r;
212             coords[2][0] =  1.0f;   coords[2][1] = -f.b;   coords[2][2] = -f.l;
213             coords[3][0] =  1.0f;   coords[3][1] = -f.b;   coords[3][2] = -f.r;
214             break;
215
216         case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
217             info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
218             info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
219             info->tex_type = tex_cube;
220             cube_coords_float(&rect, w, h, &f);
221
222             coords[0][0] = -1.0f;   coords[0][1] = -f.t;   coords[0][2] = f.l;
223             coords[1][0] = -1.0f;   coords[1][1] = -f.t;   coords[1][2] = f.r;
224             coords[2][0] = -1.0f;   coords[2][1] = -f.b;   coords[2][2] = f.l;
225             coords[3][0] = -1.0f;   coords[3][1] = -f.b;   coords[3][2] = f.r;
226             break;
227
228         case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
229             info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
230             info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
231             info->tex_type = tex_cube;
232             cube_coords_float(&rect, w, h, &f);
233
234             coords[0][0] = f.l;   coords[0][1] =  1.0f;   coords[0][2] = f.t;
235             coords[1][0] = f.r;   coords[1][1] =  1.0f;   coords[1][2] = f.t;
236             coords[2][0] = f.l;   coords[2][1] =  1.0f;   coords[2][2] = f.b;
237             coords[3][0] = f.r;   coords[3][1] =  1.0f;   coords[3][2] = f.b;
238             break;
239
240         case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
241             info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
242             info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
243             info->tex_type = tex_cube;
244             cube_coords_float(&rect, w, h, &f);
245
246             coords[0][0] = f.l;   coords[0][1] = -1.0f;   coords[0][2] = -f.t;
247             coords[1][0] = f.r;   coords[1][1] = -1.0f;   coords[1][2] = -f.t;
248             coords[2][0] = f.l;   coords[2][1] = -1.0f;   coords[2][2] = -f.b;
249             coords[3][0] = f.r;   coords[3][1] = -1.0f;   coords[3][2] = -f.b;
250             break;
251
252         case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
253             info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
254             info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
255             info->tex_type = tex_cube;
256             cube_coords_float(&rect, w, h, &f);
257
258             coords[0][0] = f.l;   coords[0][1] = -f.t;   coords[0][2] =  1.0f;
259             coords[1][0] = f.r;   coords[1][1] = -f.t;   coords[1][2] =  1.0f;
260             coords[2][0] = f.l;   coords[2][1] = -f.b;   coords[2][2] =  1.0f;
261             coords[3][0] = f.r;   coords[3][1] = -f.b;   coords[3][2] =  1.0f;
262             break;
263
264         case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
265             info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
266             info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
267             info->tex_type = tex_cube;
268             cube_coords_float(&rect, w, h, &f);
269
270             coords[0][0] = -f.l;   coords[0][1] = -f.t;   coords[0][2] = -1.0f;
271             coords[1][0] = -f.r;   coords[1][1] = -f.t;   coords[1][2] = -1.0f;
272             coords[2][0] = -f.l;   coords[2][1] = -f.b;   coords[2][2] = -1.0f;
273             coords[3][0] = -f.r;   coords[3][1] = -f.b;   coords[3][2] = -1.0f;
274             break;
275     }
276 }
277
278 static inline void surface_get_rect(IWineD3DSurfaceImpl *This, const RECT *rect_in, RECT *rect_out)
279 {
280     if (rect_in)
281         *rect_out = *rect_in;
282     else
283     {
284         rect_out->left = 0;
285         rect_out->top = 0;
286         rect_out->right = This->currentDesc.Width;
287         rect_out->bottom = This->currentDesc.Height;
288     }
289 }
290
291 /* GL locking and context activation is done by the caller */
292 void draw_textured_quad(IWineD3DSurfaceImpl *src_surface, const RECT *src_rect, const RECT *dst_rect, WINED3DTEXTUREFILTERTYPE Filter)
293 {
294     struct blt_info info;
295
296     surface_get_blt_info(src_surface->texture_target, src_rect, src_surface->pow2Width, src_surface->pow2Height, &info);
297
298     glEnable(info.bind_target);
299     checkGLcall("glEnable(bind_target)");
300
301     /* Bind the texture */
302     glBindTexture(info.bind_target, src_surface->texture_name);
303     checkGLcall("glBindTexture");
304
305     /* Filtering for StretchRect */
306     glTexParameteri(info.bind_target, GL_TEXTURE_MAG_FILTER,
307             wined3d_gl_mag_filter(magLookup, Filter));
308     checkGLcall("glTexParameteri");
309     glTexParameteri(info.bind_target, GL_TEXTURE_MIN_FILTER,
310             wined3d_gl_min_mip_filter(minMipLookup, Filter, WINED3DTEXF_NONE));
311     checkGLcall("glTexParameteri");
312     glTexParameteri(info.bind_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
313     glTexParameteri(info.bind_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
314     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
315     checkGLcall("glTexEnvi");
316
317     /* Draw a quad */
318     glBegin(GL_TRIANGLE_STRIP);
319     glTexCoord3fv(info.coords[0]);
320     glVertex2i(dst_rect->left, dst_rect->top);
321
322     glTexCoord3fv(info.coords[1]);
323     glVertex2i(dst_rect->right, dst_rect->top);
324
325     glTexCoord3fv(info.coords[2]);
326     glVertex2i(dst_rect->left, dst_rect->bottom);
327
328     glTexCoord3fv(info.coords[3]);
329     glVertex2i(dst_rect->right, dst_rect->bottom);
330     glEnd();
331
332     /* Unbind the texture */
333     glBindTexture(info.bind_target, 0);
334     checkGLcall("glBindTexture(info->bind_target, 0)");
335
336     /* We changed the filtering settings on the texture. Inform the
337      * container about this to get the filters reset properly next draw. */
338     if (src_surface->container.type == WINED3D_CONTAINER_TEXTURE)
339     {
340         IWineD3DBaseTextureImpl *texture = src_surface->container.u.texture;
341         texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
342         texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
343         texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
344     }
345 }
346
347 HRESULT surface_init(IWineD3DSurfaceImpl *surface, WINED3DSURFTYPE surface_type, UINT alignment,
348         UINT width, UINT height, UINT level, BOOL lockable, BOOL discard, WINED3DMULTISAMPLE_TYPE multisample_type,
349         UINT multisample_quality, IWineD3DDeviceImpl *device, DWORD usage, enum wined3d_format_id format_id,
350         WINED3DPOOL pool, void *parent, const struct wined3d_parent_ops *parent_ops)
351 {
352     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
353     const struct wined3d_format *format = wined3d_get_format(gl_info, format_id);
354     void (*cleanup)(IWineD3DSurfaceImpl *This);
355     unsigned int resource_size;
356     HRESULT hr;
357
358     if (multisample_quality > 0)
359     {
360         FIXME("multisample_quality set to %u, substituting 0\n", multisample_quality);
361         multisample_quality = 0;
362     }
363
364     /* FIXME: Check that the format is supported by the device. */
365
366     resource_size = wined3d_format_calculate_size(format, alignment, width, height);
367
368     /* Look at the implementation and set the correct Vtable. */
369     switch (surface_type)
370     {
371         case SURFACE_OPENGL:
372             surface->lpVtbl = &IWineD3DSurface_Vtbl;
373             cleanup = surface_cleanup;
374             break;
375
376         case SURFACE_GDI:
377             surface->lpVtbl = &IWineGDISurface_Vtbl;
378             cleanup = surface_gdi_cleanup;
379             break;
380
381         default:
382             ERR("Requested unknown surface implementation %#x.\n", surface_type);
383             return WINED3DERR_INVALIDCALL;
384     }
385
386     hr = resource_init((IWineD3DResource *)surface, WINED3DRTYPE_SURFACE,
387             device, resource_size, usage, format, pool, parent, parent_ops);
388     if (FAILED(hr))
389     {
390         WARN("Failed to initialize resource, returning %#x.\n", hr);
391         return hr;
392     }
393
394     /* "Standalone" surface. */
395     surface_set_container(surface, WINED3D_CONTAINER_NONE, NULL);
396
397     surface->currentDesc.Width = width;
398     surface->currentDesc.Height = height;
399     surface->currentDesc.MultiSampleType = multisample_type;
400     surface->currentDesc.MultiSampleQuality = multisample_quality;
401     surface->texture_level = level;
402     list_init(&surface->overlays);
403
404     /* Flags */
405     surface->Flags = SFLAG_NORMCOORD; /* Default to normalized coords. */
406     if (discard) surface->Flags |= SFLAG_DISCARD;
407     if (lockable || format_id == WINED3DFMT_D16_LOCKABLE) surface->Flags |= SFLAG_LOCKABLE;
408
409     /* Quick lockable sanity check.
410      * TODO: remove this after surfaces, usage and lockability have been debugged properly
411      * this function is too deep to need to care about things like this.
412      * Levels need to be checked too, since they all affect what can be done. */
413     switch (pool)
414     {
415         case WINED3DPOOL_SCRATCH:
416             if(!lockable)
417             {
418                 FIXME("Called with a pool of SCRATCH and a lockable of FALSE "
419                         "which are mutually exclusive, setting lockable to TRUE.\n");
420                 lockable = TRUE;
421             }
422             break;
423
424         case WINED3DPOOL_SYSTEMMEM:
425             if (!lockable)
426                 FIXME("Called with a pool of SYSTEMMEM and a lockable of FALSE, this is acceptable but unexpected.\n");
427             break;
428
429         case WINED3DPOOL_MANAGED:
430             if (usage & WINED3DUSAGE_DYNAMIC)
431                 FIXME("Called with a pool of MANAGED and a usage of DYNAMIC which are mutually exclusive.\n");
432             break;
433
434         case WINED3DPOOL_DEFAULT:
435             if (lockable && !(usage & (WINED3DUSAGE_DYNAMIC | WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL)))
436                 WARN("Creating a lockable surface with a POOL of DEFAULT, that doesn't specify DYNAMIC usage.\n");
437             break;
438
439         default:
440             FIXME("Unknown pool %#x.\n", pool);
441             break;
442     };
443
444     if (usage & WINED3DUSAGE_RENDERTARGET && pool != WINED3DPOOL_DEFAULT)
445     {
446         FIXME("Trying to create a render target that isn't in the default pool.\n");
447     }
448
449     /* Mark the texture as dirty so that it gets loaded first time around. */
450     surface_add_dirty_rect(surface, NULL);
451     list_init(&surface->renderbuffers);
452
453     TRACE("surface %p, memory %p, size %u\n", surface, surface->resource.allocatedMemory, surface->resource.size);
454
455     /* Call the private setup routine */
456     hr = IWineD3DSurface_PrivateSetup((IWineD3DSurface *)surface);
457     if (FAILED(hr))
458     {
459         ERR("Private setup failed, returning %#x\n", hr);
460         cleanup(surface);
461         return hr;
462     }
463
464     return hr;
465 }
466
467 static void surface_force_reload(IWineD3DSurfaceImpl *surface)
468 {
469     surface->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
470 }
471
472 void surface_set_texture_name(IWineD3DSurfaceImpl *surface, GLuint new_name, BOOL srgb)
473 {
474     GLuint *name;
475     DWORD flag;
476
477     TRACE("surface %p, new_name %u, srgb %#x.\n", surface, new_name, srgb);
478
479     if(srgb)
480     {
481         name = &surface->texture_name_srgb;
482         flag = SFLAG_INSRGBTEX;
483     }
484     else
485     {
486         name = &surface->texture_name;
487         flag = SFLAG_INTEXTURE;
488     }
489
490     if (!*name && new_name)
491     {
492         /* FIXME: We shouldn't need to remove SFLAG_INTEXTURE if the
493          * surface has no texture name yet. See if we can get rid of this. */
494         if (surface->Flags & flag)
495             ERR("Surface has %s set, but no texture name.\n", debug_surflocation(flag));
496         surface_modify_location(surface, flag, FALSE);
497     }
498
499     *name = new_name;
500     surface_force_reload(surface);
501 }
502
503 void surface_set_texture_target(IWineD3DSurfaceImpl *surface, GLenum target)
504 {
505     TRACE("surface %p, target %#x.\n", surface, target);
506
507     if (surface->texture_target != target)
508     {
509         if (target == GL_TEXTURE_RECTANGLE_ARB)
510         {
511             surface->Flags &= ~SFLAG_NORMCOORD;
512         }
513         else if (surface->texture_target == GL_TEXTURE_RECTANGLE_ARB)
514         {
515             surface->Flags |= SFLAG_NORMCOORD;
516         }
517     }
518     surface->texture_target = target;
519     surface_force_reload(surface);
520 }
521
522 /* Context activation is done by the caller. */
523 static void surface_bind_and_dirtify(IWineD3DSurfaceImpl *This, BOOL srgb) {
524     DWORD active_sampler;
525
526     /* We don't need a specific texture unit, but after binding the texture the current unit is dirty.
527      * Read the unit back instead of switching to 0, this avoids messing around with the state manager's
528      * gl states. The current texture unit should always be a valid one.
529      *
530      * To be more specific, this is tricky because we can implicitly be called
531      * from sampler() in state.c. This means we can't touch anything other than
532      * whatever happens to be the currently active texture, or we would risk
533      * marking already applied sampler states dirty again.
534      *
535      * TODO: Track the current active texture per GL context instead of using glGet
536      */
537     GLint active_texture;
538     ENTER_GL();
539     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
540     LEAVE_GL();
541     active_sampler = This->resource.device->rev_tex_unit_map[active_texture - GL_TEXTURE0_ARB];
542
543     if (active_sampler != WINED3D_UNMAPPED_STAGE)
544     {
545         IWineD3DDeviceImpl_MarkStateDirty(This->resource.device, STATE_SAMPLER(active_sampler));
546     }
547     IWineD3DSurface_BindTexture((IWineD3DSurface *)This, srgb);
548 }
549
550 /* This function checks if the primary render target uses the 8bit paletted format. */
551 static BOOL primary_render_target_is_p8(IWineD3DDeviceImpl *device)
552 {
553     if (device->render_targets && device->render_targets[0])
554     {
555         IWineD3DSurfaceImpl *render_target = device->render_targets[0];
556         if ((render_target->resource.usage & WINED3DUSAGE_RENDERTARGET)
557                 && (render_target->resource.format->id == WINED3DFMT_P8_UINT))
558             return TRUE;
559     }
560     return FALSE;
561 }
562
563 /* This call just downloads data, the caller is responsible for binding the
564  * correct texture. */
565 /* Context activation is done by the caller. */
566 static void surface_download_data(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info)
567 {
568     const struct wined3d_format *format = This->resource.format;
569
570     /* Only support read back of converted P8 surfaces */
571     if (This->Flags & SFLAG_CONVERTED && format->id != WINED3DFMT_P8_UINT)
572     {
573         FIXME("Readback conversion not supported for format %s.\n", debug_d3dformat(format->id));
574         return;
575     }
576
577     ENTER_GL();
578
579     if (format->Flags & WINED3DFMT_FLAG_COMPRESSED)
580     {
581         TRACE("(%p) : Calling glGetCompressedTexImageARB level %d, format %#x, type %#x, data %p.\n",
582                 This, This->texture_level, format->glFormat, format->glType,
583                 This->resource.allocatedMemory);
584
585         if (This->Flags & SFLAG_PBO)
586         {
587             GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
588             checkGLcall("glBindBufferARB");
589             GL_EXTCALL(glGetCompressedTexImageARB(This->texture_target, This->texture_level, NULL));
590             checkGLcall("glGetCompressedTexImageARB");
591             GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
592             checkGLcall("glBindBufferARB");
593         }
594         else
595         {
596             GL_EXTCALL(glGetCompressedTexImageARB(This->texture_target,
597                     This->texture_level, This->resource.allocatedMemory));
598             checkGLcall("glGetCompressedTexImageARB");
599         }
600
601         LEAVE_GL();
602     } else {
603         void *mem;
604         GLenum gl_format = format->glFormat;
605         GLenum gl_type = format->glType;
606         int src_pitch = 0;
607         int dst_pitch = 0;
608
609         /* In case of P8 the index is stored in the alpha component if the primary render target uses P8 */
610         if (format->id == WINED3DFMT_P8_UINT && primary_render_target_is_p8(This->resource.device))
611         {
612             gl_format = GL_ALPHA;
613             gl_type = GL_UNSIGNED_BYTE;
614         }
615
616         if (This->Flags & SFLAG_NONPOW2) {
617             unsigned char alignment = This->resource.device->surface_alignment;
618             src_pitch = format->byte_count * This->pow2Width;
619             dst_pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);
620             src_pitch = (src_pitch + alignment - 1) & ~(alignment - 1);
621             mem = HeapAlloc(GetProcessHeap(), 0, src_pitch * This->pow2Height);
622         } else {
623             mem = This->resource.allocatedMemory;
624         }
625
626         TRACE("(%p) : Calling glGetTexImage level %d, format %#x, type %#x, data %p\n",
627                 This, This->texture_level, gl_format, gl_type, mem);
628
629         if(This->Flags & SFLAG_PBO) {
630             GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
631             checkGLcall("glBindBufferARB");
632
633             glGetTexImage(This->texture_target, This->texture_level, gl_format, gl_type, NULL);
634             checkGLcall("glGetTexImage");
635
636             GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
637             checkGLcall("glBindBufferARB");
638         } else {
639             glGetTexImage(This->texture_target, This->texture_level, gl_format, gl_type, mem);
640             checkGLcall("glGetTexImage");
641         }
642         LEAVE_GL();
643
644         if (This->Flags & SFLAG_NONPOW2) {
645             const BYTE *src_data;
646             BYTE *dst_data;
647             UINT y;
648             /*
649              * Some games (e.g. warhammer 40k) don't work properly with the odd pitches, preventing
650              * the surface pitch from being used to box non-power2 textures. Instead we have to use a hack to
651              * repack the texture so that the bpp * width pitch can be used instead of bpp * pow2width.
652              *
653              * We're doing this...
654              *
655              * instead of boxing the texture :
656              * |<-texture width ->|  -->pow2width|   /\
657              * |111111111111111111|              |   |
658              * |222 Texture 222222| boxed empty  | texture height
659              * |3333 Data 33333333|              |   |
660              * |444444444444444444|              |   \/
661              * -----------------------------------   |
662              * |     boxed  empty | boxed empty  | pow2height
663              * |                  |              |   \/
664              * -----------------------------------
665              *
666              *
667              * we're repacking the data to the expected texture width
668              *
669              * |<-texture width ->|  -->pow2width|   /\
670              * |111111111111111111222222222222222|   |
671              * |222333333333333333333444444444444| texture height
672              * |444444                           |   |
673              * |                                 |   \/
674              * |                                 |   |
675              * |            empty                | pow2height
676              * |                                 |   \/
677              * -----------------------------------
678              *
679              * == is the same as
680              *
681              * |<-texture width ->|    /\
682              * |111111111111111111|
683              * |222222222222222222|texture height
684              * |333333333333333333|
685              * |444444444444444444|    \/
686              * --------------------
687              *
688              * this also means that any references to allocatedMemory should work with the data as if were a
689              * standard texture with a non-power2 width instead of texture boxed up to be a power2 texture.
690              *
691              * internally the texture is still stored in a boxed format so any references to textureName will
692              * get a boxed texture with width pow2width and not a texture of width currentDesc.Width.
693              *
694              * Performance should not be an issue, because applications normally do not lock the surfaces when
695              * rendering. If an app does, the SFLAG_DYNLOCK flag will kick in and the memory copy won't be released,
696              * and doesn't have to be re-read.
697              */
698             src_data = mem;
699             dst_data = This->resource.allocatedMemory;
700             TRACE("(%p) : Repacking the surface data from pitch %d to pitch %d\n", This, src_pitch, dst_pitch);
701             for (y = 1 ; y < This->currentDesc.Height; y++) {
702                 /* skip the first row */
703                 src_data += src_pitch;
704                 dst_data += dst_pitch;
705                 memcpy(dst_data, src_data, dst_pitch);
706             }
707
708             HeapFree(GetProcessHeap(), 0, mem);
709         }
710     }
711
712     /* Surface has now been downloaded */
713     This->Flags |= SFLAG_INSYSMEM;
714 }
715
716 /* This call just uploads data, the caller is responsible for binding the
717  * correct texture. */
718 /* Context activation is done by the caller. */
719 static void surface_upload_data(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
720         const struct wined3d_format *format, BOOL srgb, const GLvoid *data)
721 {
722     GLsizei width = This->currentDesc.Width;
723     GLsizei height = This->currentDesc.Height;
724     GLenum internal;
725
726     if (srgb)
727     {
728         internal = format->glGammaInternal;
729     }
730     else if (This->resource.usage & WINED3DUSAGE_RENDERTARGET && surface_is_offscreen(This))
731     {
732         internal = format->rtInternal;
733     }
734     else
735     {
736         internal = format->glInternal;
737     }
738
739     TRACE("This %p, internal %#x, width %d, height %d, format %#x, type %#x, data %p.\n",
740             This, internal, width, height, format->glFormat, format->glType, data);
741     TRACE("target %#x, level %u, resource size %u.\n",
742             This->texture_target, This->texture_level, This->resource.size);
743
744     if (format->heightscale != 1.0f && format->heightscale != 0.0f) height *= format->heightscale;
745
746     ENTER_GL();
747
748     if (This->Flags & SFLAG_PBO)
749     {
750         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
751         checkGLcall("glBindBufferARB");
752
753         TRACE("(%p) pbo: %#x, data: %p.\n", This, This->pbo, data);
754         data = NULL;
755     }
756
757     if (format->Flags & WINED3DFMT_FLAG_COMPRESSED)
758     {
759         TRACE("Calling glCompressedTexSubImage2DARB.\n");
760
761         GL_EXTCALL(glCompressedTexSubImage2DARB(This->texture_target, This->texture_level,
762                 0, 0, width, height, internal, This->resource.size, data));
763         checkGLcall("glCompressedTexSubImage2DARB");
764     }
765     else
766     {
767         TRACE("Calling glTexSubImage2D.\n");
768
769         glTexSubImage2D(This->texture_target, This->texture_level,
770                 0, 0, width, height, format->glFormat, format->glType, data);
771         checkGLcall("glTexSubImage2D");
772     }
773
774     if (This->Flags & SFLAG_PBO)
775     {
776         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
777         checkGLcall("glBindBufferARB");
778     }
779
780     LEAVE_GL();
781
782     if (gl_info->quirks & WINED3D_QUIRK_FBO_TEX_UPDATE)
783     {
784         IWineD3DDeviceImpl *device = This->resource.device;
785         unsigned int i;
786
787         for (i = 0; i < device->numContexts; ++i)
788         {
789             context_surface_update(device->contexts[i], This);
790         }
791     }
792 }
793
794 /* This call just allocates the texture, the caller is responsible for binding
795  * the correct texture. */
796 /* Context activation is done by the caller. */
797 static void surface_allocate_surface(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
798         const struct wined3d_format *format, BOOL srgb)
799 {
800     BOOL enable_client_storage = FALSE;
801     GLsizei width = This->pow2Width;
802     GLsizei height = This->pow2Height;
803     const BYTE *mem = NULL;
804     GLenum internal;
805
806     if (srgb)
807     {
808         internal = format->glGammaInternal;
809     }
810     else if (This->resource.usage & WINED3DUSAGE_RENDERTARGET && surface_is_offscreen(This))
811     {
812         internal = format->rtInternal;
813     }
814     else
815     {
816         internal = format->glInternal;
817     }
818
819     if (format->heightscale != 1.0f && format->heightscale != 0.0f) height *= format->heightscale;
820
821     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",
822             This, This->texture_target, This->texture_level, debug_d3dformat(format->id),
823             internal, width, height, format->glFormat, format->glType);
824
825     ENTER_GL();
826
827     if (gl_info->supported[APPLE_CLIENT_STORAGE])
828     {
829         if (This->Flags & (SFLAG_NONPOW2 | SFLAG_DIBSECTION | SFLAG_CONVERTED)
830                 || !This->resource.allocatedMemory)
831         {
832             /* In some cases we want to disable client storage.
833              * SFLAG_NONPOW2 has a bigger opengl texture than the client memory, and different pitches
834              * SFLAG_DIBSECTION: Dibsections may have read / write protections on the memory. Avoid issues...
835              * SFLAG_CONVERTED: The conversion destination memory is freed after loading the surface
836              * allocatedMemory == NULL: Not defined in the extension. Seems to disable client storage effectively
837              */
838             glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
839             checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
840             This->Flags &= ~SFLAG_CLIENT;
841             enable_client_storage = TRUE;
842         } else {
843             This->Flags |= SFLAG_CLIENT;
844
845             /* Point opengl to our allocated texture memory. Do not use resource.allocatedMemory here because
846              * it might point into a pbo. Instead use heapMemory, but get the alignment right.
847              */
848             mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
849         }
850     }
851
852     if (format->Flags & WINED3DFMT_FLAG_COMPRESSED && mem)
853     {
854         GL_EXTCALL(glCompressedTexImage2DARB(This->texture_target, This->texture_level,
855                 internal, width, height, 0, This->resource.size, mem));
856         checkGLcall("glCompressedTexImage2DARB");
857     }
858     else
859     {
860         glTexImage2D(This->texture_target, This->texture_level,
861                 internal, width, height, 0, format->glFormat, format->glType, mem);
862         checkGLcall("glTexImage2D");
863     }
864
865     if(enable_client_storage) {
866         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
867         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
868     }
869     LEAVE_GL();
870 }
871
872 /* In D3D the depth stencil dimensions have to be greater than or equal to the
873  * render target dimensions. With FBOs, the dimensions have to be an exact match. */
874 /* TODO: We should synchronize the renderbuffer's content with the texture's content. */
875 /* GL locking is done by the caller */
876 void surface_set_compatible_renderbuffer(IWineD3DSurfaceImpl *surface, unsigned int width, unsigned int height)
877 {
878     const struct wined3d_gl_info *gl_info = &surface->resource.device->adapter->gl_info;
879     renderbuffer_entry_t *entry;
880     GLuint renderbuffer = 0;
881     unsigned int src_width, src_height;
882
883     src_width = surface->pow2Width;
884     src_height = surface->pow2Height;
885
886     /* A depth stencil smaller than the render target is not valid */
887     if (width > src_width || height > src_height) return;
888
889     /* Remove any renderbuffer set if the sizes match */
890     if (gl_info->supported[ARB_FRAMEBUFFER_OBJECT]
891             || (width == src_width && height == src_height))
892     {
893         surface->current_renderbuffer = NULL;
894         return;
895     }
896
897     /* Look if we've already got a renderbuffer of the correct dimensions */
898     LIST_FOR_EACH_ENTRY(entry, &surface->renderbuffers, renderbuffer_entry_t, entry)
899     {
900         if (entry->width == width && entry->height == height)
901         {
902             renderbuffer = entry->id;
903             surface->current_renderbuffer = entry;
904             break;
905         }
906     }
907
908     if (!renderbuffer)
909     {
910         gl_info->fbo_ops.glGenRenderbuffers(1, &renderbuffer);
911         gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
912         gl_info->fbo_ops.glRenderbufferStorage(GL_RENDERBUFFER,
913                 surface->resource.format->glInternal, width, height);
914
915         entry = HeapAlloc(GetProcessHeap(), 0, sizeof(renderbuffer_entry_t));
916         entry->width = width;
917         entry->height = height;
918         entry->id = renderbuffer;
919         list_add_head(&surface->renderbuffers, &entry->entry);
920
921         surface->current_renderbuffer = entry;
922     }
923
924     checkGLcall("set_compatible_renderbuffer");
925 }
926
927 GLenum surface_get_gl_buffer(IWineD3DSurfaceImpl *surface)
928 {
929     IWineD3DSwapChainImpl *swapchain = surface->container.u.swapchain;
930
931     TRACE("surface %p.\n", surface);
932
933     if (surface->container.type != WINED3D_CONTAINER_SWAPCHAIN)
934     {
935         ERR("Surface %p is not on a swapchain.\n", surface);
936         return GL_NONE;
937     }
938
939     if (swapchain->back_buffers && swapchain->back_buffers[0] == surface)
940     {
941         if (swapchain->render_to_fbo)
942         {
943             TRACE("Returning GL_COLOR_ATTACHMENT0\n");
944             return GL_COLOR_ATTACHMENT0;
945         }
946         TRACE("Returning GL_BACK\n");
947         return GL_BACK;
948     }
949     else if (surface == swapchain->front_buffer)
950     {
951         TRACE("Returning GL_FRONT\n");
952         return GL_FRONT;
953     }
954
955     FIXME("Higher back buffer, returning GL_BACK\n");
956     return GL_BACK;
957 }
958
959 /* Slightly inefficient way to handle multiple dirty rects but it works :) */
960 void surface_add_dirty_rect(IWineD3DSurfaceImpl *surface, const RECT *dirty_rect)
961 {
962     TRACE("surface %p, dirty_rect %s.\n", surface, wine_dbgstr_rect(dirty_rect));
963
964     if (!(surface->Flags & SFLAG_INSYSMEM) && (surface->Flags & SFLAG_INTEXTURE))
965         /* No partial locking for textures yet. */
966         surface_load_location(surface, SFLAG_INSYSMEM, NULL);
967
968     surface_modify_location(surface, SFLAG_INSYSMEM, TRUE);
969     if (dirty_rect)
970     {
971         surface->dirtyRect.left = min(surface->dirtyRect.left, dirty_rect->left);
972         surface->dirtyRect.top = min(surface->dirtyRect.top, dirty_rect->top);
973         surface->dirtyRect.right = max(surface->dirtyRect.right, dirty_rect->right);
974         surface->dirtyRect.bottom = max(surface->dirtyRect.bottom, dirty_rect->bottom);
975     }
976     else
977     {
978         surface->dirtyRect.left = 0;
979         surface->dirtyRect.top = 0;
980         surface->dirtyRect.right = surface->currentDesc.Width;
981         surface->dirtyRect.bottom = surface->currentDesc.Height;
982     }
983
984     /* if the container is a basetexture then mark it dirty. */
985     if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
986     {
987         TRACE("Passing to container.\n");
988         IWineD3DBaseTexture_SetDirty((IWineD3DBaseTexture *)surface->container.u.texture, TRUE);
989     }
990 }
991
992 static BOOL surface_convert_color_to_float(IWineD3DSurfaceImpl *surface, DWORD color, WINED3DCOLORVALUE *float_color)
993 {
994     const struct wined3d_format *format = surface->resource.format;
995     IWineD3DDeviceImpl *device = surface->resource.device;
996
997     switch (format->id)
998     {
999         case WINED3DFMT_P8_UINT:
1000             if (surface->palette)
1001             {
1002                 float_color->r = surface->palette->palents[color].peRed / 255.0f;
1003                 float_color->g = surface->palette->palents[color].peGreen / 255.0f;
1004                 float_color->b = surface->palette->palents[color].peBlue / 255.0f;
1005             }
1006             else
1007             {
1008                 float_color->r = 0.0f;
1009                 float_color->g = 0.0f;
1010                 float_color->b = 0.0f;
1011             }
1012             float_color->a = primary_render_target_is_p8(device) ? color / 255.0f : 1.0f;
1013             break;
1014
1015         case WINED3DFMT_B5G6R5_UNORM:
1016             float_color->r = ((color >> 11) & 0x1f) / 31.0f;
1017             float_color->g = ((color >> 5) & 0x3f) / 63.0f;
1018             float_color->b = (color & 0x1f) / 31.0f;
1019             float_color->a = 1.0f;
1020             break;
1021
1022         case WINED3DFMT_B8G8R8_UNORM:
1023         case WINED3DFMT_B8G8R8X8_UNORM:
1024             float_color->r = D3DCOLOR_R(color);
1025             float_color->g = D3DCOLOR_G(color);
1026             float_color->b = D3DCOLOR_B(color);
1027             float_color->a = 1.0f;
1028             break;
1029
1030         case WINED3DFMT_B8G8R8A8_UNORM:
1031             float_color->r = D3DCOLOR_R(color);
1032             float_color->g = D3DCOLOR_G(color);
1033             float_color->b = D3DCOLOR_B(color);
1034             float_color->a = D3DCOLOR_A(color);
1035             break;
1036
1037         default:
1038             ERR("Unhandled conversion from %s to floating point.\n", debug_d3dformat(format->id));
1039             return FALSE;
1040     }
1041
1042     return TRUE;
1043 }
1044
1045 /* Do not call while under the GL lock. */
1046 static ULONG WINAPI IWineD3DSurfaceImpl_Release(IWineD3DSurface *iface)
1047 {
1048     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1049     ULONG ref = InterlockedDecrement(&This->resource.ref);
1050     TRACE("(%p) : Releasing from %d\n", This, ref + 1);
1051
1052     if (!ref)
1053     {
1054         surface_cleanup(This);
1055         This->resource.parent_ops->wined3d_object_destroyed(This->resource.parent);
1056
1057         TRACE("(%p) Released.\n", This);
1058         HeapFree(GetProcessHeap(), 0, This);
1059     }
1060
1061     return ref;
1062 }
1063
1064 /* ****************************************************
1065    IWineD3DSurface IWineD3DResource parts follow
1066    **************************************************** */
1067
1068 /* Do not call while under the GL lock. */
1069 void surface_internal_preload(IWineD3DSurfaceImpl *surface, enum WINED3DSRGB srgb)
1070 {
1071     IWineD3DDeviceImpl *device = surface->resource.device;
1072
1073     TRACE("iface %p, srgb %#x.\n", surface, srgb);
1074
1075     if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
1076     {
1077         IWineD3DBaseTextureImpl *texture = surface->container.u.texture;
1078
1079         TRACE("Passing to container.\n");
1080         texture->baseTexture.internal_preload((IWineD3DBaseTexture *)texture, srgb);
1081     }
1082     else
1083     {
1084         struct wined3d_context *context = NULL;
1085
1086         TRACE("(%p) : About to load surface\n", surface);
1087
1088         if (!device->isInDraw) context = context_acquire(device, NULL);
1089
1090         if (surface->resource.format->id == WINED3DFMT_P8_UINT
1091                 || surface->resource.format->id == WINED3DFMT_P8_UINT_A8_UNORM)
1092         {
1093             if (palette9_changed(surface))
1094             {
1095                 TRACE("Reloading surface because the d3d8/9 palette was changed\n");
1096                 /* TODO: This is not necessarily needed with hw palettized texture support */
1097                 surface_load_location(surface, SFLAG_INSYSMEM, NULL);
1098                 /* Make sure the texture is reloaded because of the palette change, this kills performance though :( */
1099                 surface_modify_location(surface, SFLAG_INTEXTURE, FALSE);
1100             }
1101         }
1102
1103         IWineD3DSurface_LoadTexture((IWineD3DSurface *)surface, srgb == SRGB_SRGB ? TRUE : FALSE);
1104
1105         if (surface->resource.pool == WINED3DPOOL_DEFAULT)
1106         {
1107             /* Tell opengl to try and keep this texture in video ram (well mostly) */
1108             GLclampf tmp;
1109             tmp = 0.9f;
1110             ENTER_GL();
1111             glPrioritizeTextures(1, &surface->texture_name, &tmp);
1112             LEAVE_GL();
1113         }
1114
1115         if (context) context_release(context);
1116     }
1117 }
1118
1119 static void WINAPI IWineD3DSurfaceImpl_PreLoad(IWineD3DSurface *iface)
1120 {
1121     surface_internal_preload((IWineD3DSurfaceImpl *)iface, SRGB_ANY);
1122 }
1123
1124 /* Context activation is done by the caller. */
1125 static void surface_remove_pbo(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info)
1126 {
1127     This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
1128     This->resource.allocatedMemory =
1129             (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1130
1131     ENTER_GL();
1132     GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1133     checkGLcall("glBindBufferARB(GL_PIXEL_UNPACK_BUFFER, This->pbo)");
1134     GL_EXTCALL(glGetBufferSubDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0, This->resource.size, This->resource.allocatedMemory));
1135     checkGLcall("glGetBufferSubDataARB");
1136     GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
1137     checkGLcall("glDeleteBuffersARB");
1138     LEAVE_GL();
1139
1140     This->pbo = 0;
1141     This->Flags &= ~SFLAG_PBO;
1142 }
1143
1144 BOOL surface_init_sysmem(IWineD3DSurfaceImpl *surface)
1145 {
1146     if (!surface->resource.allocatedMemory)
1147     {
1148         surface->resource.heapMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1149                 surface->resource.size + RESOURCE_ALIGNMENT);
1150         if (!surface->resource.heapMemory)
1151         {
1152             ERR("Out of memory\n");
1153             return FALSE;
1154         }
1155         surface->resource.allocatedMemory =
1156             (BYTE *)(((ULONG_PTR)surface->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1157     }
1158     else
1159     {
1160         memset(surface->resource.allocatedMemory, 0, surface->resource.size);
1161     }
1162
1163     surface_modify_location(surface, SFLAG_INSYSMEM, TRUE);
1164
1165     return TRUE;
1166 }
1167
1168 /* Do not call while under the GL lock. */
1169 static void WINAPI IWineD3DSurfaceImpl_UnLoad(IWineD3DSurface *iface)
1170 {
1171     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
1172     IWineD3DDeviceImpl *device = This->resource.device;
1173     const struct wined3d_gl_info *gl_info;
1174     renderbuffer_entry_t *entry, *entry2;
1175     struct wined3d_context *context;
1176
1177     TRACE("(%p)\n", iface);
1178
1179     if(This->resource.pool == WINED3DPOOL_DEFAULT) {
1180         /* Default pool resources are supposed to be destroyed before Reset is called.
1181          * Implicit resources stay however. So this means we have an implicit render target
1182          * or depth stencil. The content may be destroyed, but we still have to tear down
1183          * opengl resources, so we cannot leave early.
1184          *
1185          * Put the surfaces into sysmem, and reset the content. The D3D content is undefined,
1186          * but we can't set the sysmem INDRAWABLE because when we're rendering the swapchain
1187          * or the depth stencil into an FBO the texture or render buffer will be removed
1188          * and all flags get lost
1189          */
1190         surface_init_sysmem(This);
1191     }
1192     else
1193     {
1194         /* Load the surface into system memory */
1195         surface_load_location(This, SFLAG_INSYSMEM, NULL);
1196         surface_modify_location(This, SFLAG_INDRAWABLE, FALSE);
1197     }
1198     surface_modify_location(This, SFLAG_INTEXTURE, FALSE);
1199     surface_modify_location(This, SFLAG_INSRGBTEX, FALSE);
1200     This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
1201
1202     context = context_acquire(device, NULL);
1203     gl_info = context->gl_info;
1204
1205     /* Destroy PBOs, but load them into real sysmem before */
1206     if (This->Flags & SFLAG_PBO)
1207         surface_remove_pbo(This, gl_info);
1208
1209     /* Destroy fbo render buffers. This is needed for implicit render targets, for
1210      * all application-created targets the application has to release the surface
1211      * before calling _Reset
1212      */
1213     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
1214         ENTER_GL();
1215         gl_info->fbo_ops.glDeleteRenderbuffers(1, &entry->id);
1216         LEAVE_GL();
1217         list_remove(&entry->entry);
1218         HeapFree(GetProcessHeap(), 0, entry);
1219     }
1220     list_init(&This->renderbuffers);
1221     This->current_renderbuffer = NULL;
1222
1223     /* If we're in a texture, the texture name belongs to the texture.
1224      * Otherwise, destroy it. */
1225     if (This->container.type != WINED3D_CONTAINER_TEXTURE)
1226     {
1227         ENTER_GL();
1228         glDeleteTextures(1, &This->texture_name);
1229         This->texture_name = 0;
1230         glDeleteTextures(1, &This->texture_name_srgb);
1231         This->texture_name_srgb = 0;
1232         LEAVE_GL();
1233     }
1234
1235     context_release(context);
1236
1237     resource_unload((IWineD3DResourceImpl *)This);
1238 }
1239
1240 /* ******************************************************
1241    IWineD3DSurface IWineD3DSurface parts follow
1242    ****************************************************** */
1243
1244 /* Read the framebuffer back into the surface */
1245 static void read_from_framebuffer(IWineD3DSurfaceImpl *This, const RECT *rect, void *dest, UINT pitch)
1246 {
1247     IWineD3DDeviceImpl *device = This->resource.device;
1248     const struct wined3d_gl_info *gl_info;
1249     struct wined3d_context *context;
1250     BYTE *mem;
1251     GLint fmt;
1252     GLint type;
1253     BYTE *row, *top, *bottom;
1254     int i;
1255     BOOL bpp;
1256     RECT local_rect;
1257     BOOL srcIsUpsideDown;
1258     GLint rowLen = 0;
1259     GLint skipPix = 0;
1260     GLint skipRow = 0;
1261
1262     if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1263         static BOOL warned = FALSE;
1264         if(!warned) {
1265             ERR("The application tries to lock the render target, but render target locking is disabled\n");
1266             warned = TRUE;
1267         }
1268         return;
1269     }
1270
1271     context = context_acquire(device, This);
1272     context_apply_blit_state(context, device);
1273     gl_info = context->gl_info;
1274
1275     ENTER_GL();
1276
1277     /* Select the correct read buffer, and give some debug output.
1278      * There is no need to keep track of the current read buffer or reset it, every part of the code
1279      * that reads sets the read buffer as desired.
1280      */
1281     if (surface_is_offscreen(This))
1282     {
1283         /* Mapping the primary render target which is not on a swapchain.
1284          * Read from the back buffer. */
1285         TRACE("Mapping offscreen render target.\n");
1286         glReadBuffer(device->offscreenBuffer);
1287         srcIsUpsideDown = TRUE;
1288     }
1289     else
1290     {
1291         /* Onscreen surfaces are always part of a swapchain */
1292         GLenum buffer = surface_get_gl_buffer(This);
1293         TRACE("Mapping %#x buffer.\n", buffer);
1294         glReadBuffer(buffer);
1295         checkGLcall("glReadBuffer");
1296         srcIsUpsideDown = FALSE;
1297     }
1298
1299     /* TODO: Get rid of the extra rectangle comparison and construction of a full surface rectangle */
1300     if(!rect) {
1301         local_rect.left = 0;
1302         local_rect.top = 0;
1303         local_rect.right = This->currentDesc.Width;
1304         local_rect.bottom = This->currentDesc.Height;
1305     } else {
1306         local_rect = *rect;
1307     }
1308     /* TODO: Get rid of the extra GetPitch call, LockRect does that too. Cache the pitch */
1309
1310     switch (This->resource.format->id)
1311     {
1312         case WINED3DFMT_P8_UINT:
1313         {
1314             if (primary_render_target_is_p8(device))
1315             {
1316                 /* In case of P8 render targets the index is stored in the alpha component */
1317                 fmt = GL_ALPHA;
1318                 type = GL_UNSIGNED_BYTE;
1319                 mem = dest;
1320                 bpp = This->resource.format->byte_count;
1321             } else {
1322                 /* GL can't return palettized data, so read ARGB pixels into a
1323                  * separate block of memory and convert them into palettized format
1324                  * in software. Slow, but if the app means to use palettized render
1325                  * targets and locks it...
1326                  *
1327                  * Use GL_RGB, GL_UNSIGNED_BYTE to read the surface for performance reasons
1328                  * Don't use GL_BGR as in the WINED3DFMT_R8G8B8 case, instead watch out
1329                  * for the color channels when palettizing the colors.
1330                  */
1331                 fmt = GL_RGB;
1332                 type = GL_UNSIGNED_BYTE;
1333                 pitch *= 3;
1334                 mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * 3);
1335                 if(!mem) {
1336                     ERR("Out of memory\n");
1337                     LEAVE_GL();
1338                     return;
1339                 }
1340                 bpp = This->resource.format->byte_count * 3;
1341             }
1342         }
1343         break;
1344
1345         default:
1346             mem = dest;
1347             fmt = This->resource.format->glFormat;
1348             type = This->resource.format->glType;
1349             bpp = This->resource.format->byte_count;
1350     }
1351
1352     if(This->Flags & SFLAG_PBO) {
1353         GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
1354         checkGLcall("glBindBufferARB");
1355         if (mem)
1356         {
1357             ERR("mem not null for pbo -- unexpected\n");
1358             mem = NULL;
1359         }
1360     }
1361
1362     /* Save old pixel store pack state */
1363     glGetIntegerv(GL_PACK_ROW_LENGTH, &rowLen);
1364     checkGLcall("glGetIntegerv");
1365     glGetIntegerv(GL_PACK_SKIP_PIXELS, &skipPix);
1366     checkGLcall("glGetIntegerv");
1367     glGetIntegerv(GL_PACK_SKIP_ROWS, &skipRow);
1368     checkGLcall("glGetIntegerv");
1369
1370     /* Setup pixel store pack state -- to glReadPixels into the correct place */
1371     glPixelStorei(GL_PACK_ROW_LENGTH, This->currentDesc.Width);
1372     checkGLcall("glPixelStorei");
1373     glPixelStorei(GL_PACK_SKIP_PIXELS, local_rect.left);
1374     checkGLcall("glPixelStorei");
1375     glPixelStorei(GL_PACK_SKIP_ROWS, local_rect.top);
1376     checkGLcall("glPixelStorei");
1377
1378     glReadPixels(local_rect.left, (!srcIsUpsideDown) ? (This->currentDesc.Height - local_rect.bottom) : local_rect.top ,
1379                  local_rect.right - local_rect.left,
1380                  local_rect.bottom - local_rect.top,
1381                  fmt, type, mem);
1382     checkGLcall("glReadPixels");
1383
1384     /* Reset previous pixel store pack state */
1385     glPixelStorei(GL_PACK_ROW_LENGTH, rowLen);
1386     checkGLcall("glPixelStorei");
1387     glPixelStorei(GL_PACK_SKIP_PIXELS, skipPix);
1388     checkGLcall("glPixelStorei");
1389     glPixelStorei(GL_PACK_SKIP_ROWS, skipRow);
1390     checkGLcall("glPixelStorei");
1391
1392     if(This->Flags & SFLAG_PBO) {
1393         GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
1394         checkGLcall("glBindBufferARB");
1395
1396         /* Check if we need to flip the image. If we need to flip use glMapBufferARB
1397          * to get a pointer to it and perform the flipping in software. This is a lot
1398          * faster than calling glReadPixels for each line. In case we want more speed
1399          * we should rerender it flipped in a FBO and read the data back from the FBO. */
1400         if(!srcIsUpsideDown) {
1401             GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1402             checkGLcall("glBindBufferARB");
1403
1404             mem = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1405             checkGLcall("glMapBufferARB");
1406         }
1407     }
1408
1409     /* TODO: Merge this with the palettization loop below for P8 targets */
1410     if(!srcIsUpsideDown) {
1411         UINT len, off;
1412         /* glReadPixels returns the image upside down, and there is no way to prevent this.
1413             Flip the lines in software */
1414         len = (local_rect.right - local_rect.left) * bpp;
1415         off = local_rect.left * bpp;
1416
1417         row = HeapAlloc(GetProcessHeap(), 0, len);
1418         if(!row) {
1419             ERR("Out of memory\n");
1420             if (This->resource.format->id == WINED3DFMT_P8_UINT) HeapFree(GetProcessHeap(), 0, mem);
1421             LEAVE_GL();
1422             return;
1423         }
1424
1425         top = mem + pitch * local_rect.top;
1426         bottom = mem + pitch * (local_rect.bottom - 1);
1427         for(i = 0; i < (local_rect.bottom - local_rect.top) / 2; i++) {
1428             memcpy(row, top + off, len);
1429             memcpy(top + off, bottom + off, len);
1430             memcpy(bottom + off, row, len);
1431             top += pitch;
1432             bottom -= pitch;
1433         }
1434         HeapFree(GetProcessHeap(), 0, row);
1435
1436         /* Unmap the temp PBO buffer */
1437         if(This->Flags & SFLAG_PBO) {
1438             GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1439             GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1440         }
1441     }
1442
1443     LEAVE_GL();
1444     context_release(context);
1445
1446     /* For P8 textures we need to perform an inverse palette lookup. This is done by searching for a palette
1447      * index which matches the RGB value. Note this isn't guaranteed to work when there are multiple entries for
1448      * the same color but we have no choice.
1449      * In case of P8 render targets, the index is stored in the alpha component so no conversion is needed.
1450      */
1451     if (This->resource.format->id == WINED3DFMT_P8_UINT && !primary_render_target_is_p8(device))
1452     {
1453         const PALETTEENTRY *pal = NULL;
1454         DWORD width = pitch / 3;
1455         int x, y, c;
1456
1457         if(This->palette) {
1458             pal = This->palette->palents;
1459         } else {
1460             ERR("Palette is missing, cannot perform inverse palette lookup\n");
1461             HeapFree(GetProcessHeap(), 0, mem);
1462             return ;
1463         }
1464
1465         for(y = local_rect.top; y < local_rect.bottom; y++) {
1466             for(x = local_rect.left; x < local_rect.right; x++) {
1467                 /*                      start              lines            pixels      */
1468                 const BYTE *blue = mem + y * pitch + x * (sizeof(BYTE) * 3);
1469                 const BYTE *green = blue  + 1;
1470                 const BYTE *red = green + 1;
1471
1472                 for(c = 0; c < 256; c++) {
1473                     if(*red   == pal[c].peRed   &&
1474                        *green == pal[c].peGreen &&
1475                        *blue  == pal[c].peBlue)
1476                     {
1477                         *((BYTE *) dest + y * width + x) = c;
1478                         break;
1479                     }
1480                 }
1481             }
1482         }
1483         HeapFree(GetProcessHeap(), 0, mem);
1484     }
1485 }
1486
1487 /* Read the framebuffer contents into a texture */
1488 static void read_from_framebuffer_texture(IWineD3DSurfaceImpl *This, BOOL srgb)
1489 {
1490     IWineD3DDeviceImpl *device = This->resource.device;
1491     const struct wined3d_gl_info *gl_info;
1492     struct wined3d_context *context;
1493
1494     if (!surface_is_offscreen(This))
1495     {
1496         /* We would need to flip onscreen surfaces, but there's no efficient
1497          * way to do that here. It makes more sense for the caller to
1498          * explicitly go through sysmem. */
1499         ERR("Not supported for onscreen targets.\n");
1500         return;
1501     }
1502
1503     /* Activate the surface to read from. In some situations it isn't the currently active target(e.g. backbuffer
1504      * locking during offscreen rendering). RESOURCELOAD is ok because glCopyTexSubImage2D isn't affected by any
1505      * states in the stateblock, and no driver was found yet that had bugs in that regard.
1506      */
1507     context = context_acquire(device, This);
1508     gl_info = context->gl_info;
1509
1510     surface_prepare_texture(This, gl_info, srgb);
1511     surface_bind_and_dirtify(This, srgb);
1512
1513     TRACE("Reading back offscreen render target %p.\n", This);
1514
1515     ENTER_GL();
1516
1517     glReadBuffer(device->offscreenBuffer);
1518     checkGLcall("glReadBuffer");
1519
1520     glCopyTexSubImage2D(This->texture_target, This->texture_level,
1521             0, 0, 0, 0, This->currentDesc.Width, This->currentDesc.Height);
1522     checkGLcall("glCopyTexSubImage2D");
1523
1524     LEAVE_GL();
1525
1526     context_release(context);
1527 }
1528
1529 /* Context activation is done by the caller. */
1530 static void surface_prepare_texture_internal(IWineD3DSurfaceImpl *surface,
1531         const struct wined3d_gl_info *gl_info, BOOL srgb)
1532 {
1533     DWORD alloc_flag = srgb ? SFLAG_SRGBALLOCATED : SFLAG_ALLOCATED;
1534     CONVERT_TYPES convert;
1535     struct wined3d_format format;
1536
1537     if (surface->Flags & alloc_flag) return;
1538
1539     d3dfmt_get_conv(surface, TRUE, TRUE, &format, &convert);
1540     if (convert != NO_CONVERSION || format.convert) surface->Flags |= SFLAG_CONVERTED;
1541     else surface->Flags &= ~SFLAG_CONVERTED;
1542
1543     surface_bind_and_dirtify(surface, srgb);
1544     surface_allocate_surface(surface, gl_info, &format, srgb);
1545     surface->Flags |= alloc_flag;
1546 }
1547
1548 /* Context activation is done by the caller. */
1549 void surface_prepare_texture(IWineD3DSurfaceImpl *surface, const struct wined3d_gl_info *gl_info, BOOL srgb)
1550 {
1551     if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
1552     {
1553         IWineD3DBaseTextureImpl *texture = surface->container.u.texture;
1554         UINT sub_count = texture->baseTexture.level_count * texture->baseTexture.layer_count;
1555         UINT i;
1556
1557         TRACE("surface %p is a subresource of texture %p.\n", surface, texture);
1558
1559         for (i = 0; i < sub_count; ++i)
1560         {
1561             IWineD3DSurfaceImpl *s = (IWineD3DSurfaceImpl *)texture->baseTexture.sub_resources[i];
1562             surface_prepare_texture_internal(s, gl_info, srgb);
1563         }
1564
1565         return;
1566     }
1567
1568     surface_prepare_texture_internal(surface, gl_info, srgb);
1569 }
1570
1571 static void surface_prepare_system_memory(IWineD3DSurfaceImpl *This)
1572 {
1573     IWineD3DDeviceImpl *device = This->resource.device;
1574     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1575
1576     /* Performance optimization: Count how often a surface is locked, if it is locked regularly do not throw away the system memory copy.
1577      * This avoids the need to download the surface from opengl all the time. The surface is still downloaded if the opengl texture is
1578      * changed
1579      */
1580     if(!(This->Flags & SFLAG_DYNLOCK)) {
1581         This->lockCount++;
1582         /* MAXLOCKCOUNT is defined in wined3d_private.h */
1583         if(This->lockCount > MAXLOCKCOUNT) {
1584             TRACE("Surface is locked regularly, not freeing the system memory copy any more\n");
1585             This->Flags |= SFLAG_DYNLOCK;
1586         }
1587     }
1588
1589     /* Create a PBO for dynamically locked surfaces but don't do it for converted or non-pow2 surfaces.
1590      * Also don't create a PBO for systemmem surfaces.
1591      */
1592     if (gl_info->supported[ARB_PIXEL_BUFFER_OBJECT] && (This->Flags & SFLAG_DYNLOCK)
1593             && !(This->Flags & (SFLAG_PBO | SFLAG_CONVERTED | SFLAG_NONPOW2))
1594             && (This->resource.pool != WINED3DPOOL_SYSTEMMEM))
1595     {
1596         GLenum error;
1597         struct wined3d_context *context;
1598
1599         context = context_acquire(device, NULL);
1600         ENTER_GL();
1601
1602         GL_EXTCALL(glGenBuffersARB(1, &This->pbo));
1603         error = glGetError();
1604         if (!This->pbo || error != GL_NO_ERROR)
1605             ERR("Failed to bind the PBO with error %s (%#x)\n", debug_glerror(error), error);
1606
1607         TRACE("Attaching pbo=%#x to (%p)\n", This->pbo, This);
1608
1609         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1610         checkGLcall("glBindBufferARB");
1611
1612         GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->resource.size + 4, This->resource.allocatedMemory, GL_STREAM_DRAW_ARB));
1613         checkGLcall("glBufferDataARB");
1614
1615         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1616         checkGLcall("glBindBufferARB");
1617
1618         /* We don't need the system memory anymore and we can't even use it for PBOs */
1619         if(!(This->Flags & SFLAG_CLIENT)) {
1620             HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
1621             This->resource.heapMemory = NULL;
1622         }
1623         This->resource.allocatedMemory = NULL;
1624         This->Flags |= SFLAG_PBO;
1625         LEAVE_GL();
1626         context_release(context);
1627     }
1628     else if (!(This->resource.allocatedMemory || This->Flags & SFLAG_PBO))
1629     {
1630         /* Whatever surface we have, make sure that there is memory allocated for the downloaded copy,
1631          * or a pbo to map
1632          */
1633         if(!This->resource.heapMemory) {
1634             This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
1635         }
1636         This->resource.allocatedMemory =
1637                 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1638         if(This->Flags & SFLAG_INSYSMEM) {
1639             ERR("Surface without memory or pbo has SFLAG_INSYSMEM set!\n");
1640         }
1641     }
1642 }
1643
1644 static HRESULT WINAPI IWineD3DSurfaceImpl_Map(IWineD3DSurface *iface,
1645         WINED3DLOCKED_RECT *pLockedRect, const RECT *pRect, DWORD Flags)
1646 {
1647     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1648     IWineD3DDeviceImpl *device = This->resource.device;
1649     const RECT *pass_rect = pRect;
1650
1651     TRACE("iface %p, locked_rect %p, rect %s, flags %#x.\n",
1652             iface, pLockedRect, wine_dbgstr_rect(pRect), Flags);
1653
1654     /* This is also done in the base class, but we have to verify this before loading any data from
1655      * gl into the sysmem copy. The PBO may be mapped, a different rectangle locked, the discard flag
1656      * may interfere, and all other bad things may happen
1657      */
1658     if (This->Flags & SFLAG_LOCKED) {
1659         WARN("Surface is already locked, returning D3DERR_INVALIDCALL\n");
1660         return WINED3DERR_INVALIDCALL;
1661     }
1662     This->Flags |= SFLAG_LOCKED;
1663
1664     if (!(This->Flags & SFLAG_LOCKABLE))
1665     {
1666         TRACE("Warning: trying to lock unlockable surf@%p\n", This);
1667     }
1668
1669     if (Flags & WINED3DLOCK_DISCARD) {
1670         /* Set SFLAG_INSYSMEM, so we'll never try to download the data from the texture. */
1671         TRACE("WINED3DLOCK_DISCARD flag passed, marking local copy as up to date\n");
1672         surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1673         This->Flags |= SFLAG_INSYSMEM;
1674         goto lock_end;
1675     }
1676
1677     if (This->Flags & SFLAG_INSYSMEM) {
1678         TRACE("Local copy is up to date, not downloading data\n");
1679         surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1680         goto lock_end;
1681     }
1682
1683     /* surface_load_location() does not check if the rectangle specifies
1684      * the full surface. Most callers don't need that, so do it here. */
1685     if (pRect && !pRect->top && !pRect->left
1686             && pRect->right == This->currentDesc.Width
1687             && pRect->bottom == This->currentDesc.Height)
1688     {
1689         pass_rect = NULL;
1690     }
1691
1692     if (!(wined3d_settings.rendertargetlock_mode == RTL_DISABLE
1693             && ((This->container.type == WINED3D_CONTAINER_SWAPCHAIN) || This == device->render_targets[0])))
1694     {
1695         surface_load_location(This, SFLAG_INSYSMEM, pass_rect);
1696     }
1697
1698 lock_end:
1699     if (This->Flags & SFLAG_PBO)
1700     {
1701         const struct wined3d_gl_info *gl_info;
1702         struct wined3d_context *context;
1703
1704         context = context_acquire(device, NULL);
1705         gl_info = context->gl_info;
1706
1707         ENTER_GL();
1708         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1709         checkGLcall("glBindBufferARB");
1710
1711         /* This shouldn't happen but could occur if some other function didn't handle the PBO properly */
1712         if(This->resource.allocatedMemory) {
1713             ERR("The surface already has PBO memory allocated!\n");
1714         }
1715
1716         This->resource.allocatedMemory = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1717         checkGLcall("glMapBufferARB");
1718
1719         /* Make sure the pbo isn't set anymore in order not to break non-pbo calls */
1720         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1721         checkGLcall("glBindBufferARB");
1722
1723         LEAVE_GL();
1724         context_release(context);
1725     }
1726
1727     if (Flags & (WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY)) {
1728         /* Don't dirtify */
1729     }
1730     else
1731     {
1732         surface_add_dirty_rect(This, pRect);
1733
1734         if (This->container.type == WINED3D_CONTAINER_TEXTURE)
1735         {
1736             TRACE("Making container dirty.\n");
1737             IWineD3DBaseTexture_SetDirty((IWineD3DBaseTexture *)This->container.u.texture, TRUE);
1738         }
1739         else
1740         {
1741             TRACE("Surface is standalone, no need to dirty the container\n");
1742         }
1743     }
1744
1745     return IWineD3DBaseSurfaceImpl_Map(iface, pLockedRect, pRect, Flags);
1746 }
1747
1748 static void flush_to_framebuffer_drawpixels(IWineD3DSurfaceImpl *This, GLenum fmt, GLenum type, UINT bpp, const BYTE *mem) {
1749     GLint  prev_store;
1750     GLint  prev_rasterpos[4];
1751     GLint skipBytes = 0;
1752     UINT pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);    /* target is argb, 4 byte */
1753     IWineD3DDeviceImpl *device = This->resource.device;
1754     const struct wined3d_gl_info *gl_info;
1755     struct wined3d_context *context;
1756
1757     /* Activate the correct context for the render target */
1758     context = context_acquire(device, This);
1759     context_apply_blit_state(context, device);
1760     gl_info = context->gl_info;
1761
1762     ENTER_GL();
1763
1764     if (!surface_is_offscreen(This))
1765     {
1766         GLenum buffer = surface_get_gl_buffer(This);
1767         TRACE("Unlocking %#x buffer.\n", buffer);
1768         context_set_draw_buffer(context, buffer);
1769     }
1770     else
1771     {
1772         /* Primary offscreen render target */
1773         TRACE("Offscreen render target.\n");
1774         context_set_draw_buffer(context, device->offscreenBuffer);
1775     }
1776
1777     glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
1778     checkGLcall("glGetIntegerv");
1779     glGetIntegerv(GL_CURRENT_RASTER_POSITION, &prev_rasterpos[0]);
1780     checkGLcall("glGetIntegerv");
1781     glPixelZoom(1.0f, -1.0f);
1782     checkGLcall("glPixelZoom");
1783
1784     /* If not fullscreen, we need to skip a number of bytes to find the next row of data */
1785     glGetIntegerv(GL_UNPACK_ROW_LENGTH, &skipBytes);
1786     glPixelStorei(GL_UNPACK_ROW_LENGTH, This->currentDesc.Width);
1787
1788     glRasterPos3i(This->lockedRect.left, This->lockedRect.top, 1);
1789     checkGLcall("glRasterPos3i");
1790
1791     /* Some drivers(radeon dri, others?) don't like exceptions during
1792      * glDrawPixels. If the surface is a DIB section, it might be in GDIMode
1793      * after ReleaseDC. Reading it will cause an exception, which x11drv will
1794      * catch to put the dib section in InSync mode, which leads to a crash
1795      * and a blocked x server on my radeon card.
1796      *
1797      * The following lines read the dib section so it is put in InSync mode
1798      * before glDrawPixels is called and the crash is prevented. There won't
1799      * be any interfering gdi accesses, because UnlockRect is called from
1800      * ReleaseDC, and the app won't use the dc any more afterwards.
1801      */
1802     if((This->Flags & SFLAG_DIBSECTION) && !(This->Flags & SFLAG_PBO)) {
1803         volatile BYTE read;
1804         read = This->resource.allocatedMemory[0];
1805     }
1806
1807     if(This->Flags & SFLAG_PBO) {
1808         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1809         checkGLcall("glBindBufferARB");
1810     }
1811
1812     /* When the surface is locked we only have to refresh the locked part else we need to update the whole image */
1813     if(This->Flags & SFLAG_LOCKED) {
1814         glDrawPixels(This->lockedRect.right - This->lockedRect.left,
1815                      (This->lockedRect.bottom - This->lockedRect.top)-1,
1816                      fmt, type,
1817                      mem + bpp * This->lockedRect.left + pitch * This->lockedRect.top);
1818         checkGLcall("glDrawPixels");
1819     } else {
1820         glDrawPixels(This->currentDesc.Width,
1821                      This->currentDesc.Height,
1822                      fmt, type, mem);
1823         checkGLcall("glDrawPixels");
1824     }
1825
1826     if(This->Flags & SFLAG_PBO) {
1827         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1828         checkGLcall("glBindBufferARB");
1829     }
1830
1831     glPixelZoom(1.0f, 1.0f);
1832     checkGLcall("glPixelZoom");
1833
1834     glRasterPos3iv(&prev_rasterpos[0]);
1835     checkGLcall("glRasterPos3iv");
1836
1837     /* Reset to previous pack row length */
1838     glPixelStorei(GL_UNPACK_ROW_LENGTH, skipBytes);
1839     checkGLcall("glPixelStorei(GL_UNPACK_ROW_LENGTH)");
1840
1841     LEAVE_GL();
1842     context_release(context);
1843 }
1844
1845 static HRESULT WINAPI IWineD3DSurfaceImpl_Unmap(IWineD3DSurface *iface)
1846 {
1847     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1848     IWineD3DDeviceImpl *device = This->resource.device;
1849     BOOL fullsurface;
1850
1851     if (!(This->Flags & SFLAG_LOCKED)) {
1852         WARN("trying to Unlock an unlocked surf@%p\n", This);
1853         return WINEDDERR_NOTLOCKED;
1854     }
1855
1856     if (This->Flags & SFLAG_PBO)
1857     {
1858         const struct wined3d_gl_info *gl_info;
1859         struct wined3d_context *context;
1860
1861         TRACE("Freeing PBO memory\n");
1862
1863         context = context_acquire(device, NULL);
1864         gl_info = context->gl_info;
1865
1866         ENTER_GL();
1867         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1868         GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1869         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1870         checkGLcall("glUnmapBufferARB");
1871         LEAVE_GL();
1872         context_release(context);
1873
1874         This->resource.allocatedMemory = NULL;
1875     }
1876
1877     TRACE("(%p) : dirtyfied(%d)\n", This, This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
1878
1879     if (This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE)) {
1880         TRACE("(%p) : Not Dirtified so nothing to do, return now\n", This);
1881         goto unlock_end;
1882     }
1883
1884     if (This->container.type == WINED3D_CONTAINER_SWAPCHAIN
1885             || (device->render_targets && This == device->render_targets[0]))
1886     {
1887         if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1888             static BOOL warned = FALSE;
1889             if(!warned) {
1890                 ERR("The application tries to write to the render target, but render target locking is disabled\n");
1891                 warned = TRUE;
1892             }
1893             goto unlock_end;
1894         }
1895
1896         if (!This->dirtyRect.left && !This->dirtyRect.top
1897                 && This->dirtyRect.right == This->currentDesc.Width
1898                 && This->dirtyRect.bottom == This->currentDesc.Height)
1899         {
1900             fullsurface = TRUE;
1901         } else {
1902             /* TODO: Proper partial rectangle tracking */
1903             fullsurface = FALSE;
1904             This->Flags |= SFLAG_INSYSMEM;
1905         }
1906
1907         switch(wined3d_settings.rendertargetlock_mode) {
1908             case RTL_READTEX:
1909                 surface_load_location(This, SFLAG_INTEXTURE, NULL /* partial texture loading not supported yet */);
1910                 /* drop through */
1911
1912             case RTL_READDRAW:
1913                 surface_load_location(This, SFLAG_INDRAWABLE, fullsurface ? NULL : &This->dirtyRect);
1914                 break;
1915         }
1916
1917         if (!fullsurface)
1918         {
1919             /* Partial rectangle tracking is not commonly implemented, it is
1920              * only done for render targets. Overwrite the flags to bring
1921              * them back into a sane state. INSYSMEM was set before to tell
1922              * surface_load_location() where to read the rectangle from.
1923              * Indrawable is set because all modifications from the partial
1924              * sysmem copy are written back to the drawable, thus the surface
1925              * is merged again in the drawable. The sysmem copy is not fully
1926              * up to date because only a subrectangle was read in Map(). */
1927             This->Flags &= ~SFLAG_INSYSMEM;
1928             This->Flags |= SFLAG_INDRAWABLE;
1929         }
1930
1931         This->dirtyRect.left   = This->currentDesc.Width;
1932         This->dirtyRect.top    = This->currentDesc.Height;
1933         This->dirtyRect.right  = 0;
1934         This->dirtyRect.bottom = 0;
1935     }
1936     else if (This == device->depth_stencil)
1937     {
1938         FIXME("Depth Stencil buffer locking is not implemented\n");
1939     } else {
1940         /* The rest should be a normal texture */
1941         /* Check if the texture is bound, if yes dirtify the sampler to force a re-upload of the texture
1942          * Can't load the texture here because PreLoad may destroy and recreate the gl texture, so sampler
1943          * states need resetting
1944          */
1945         if (This->container.type == WINED3D_CONTAINER_TEXTURE)
1946         {
1947             IWineD3DBaseTextureImpl *texture = This->container.u.texture;
1948             if (texture->baseTexture.bindCount)
1949                 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(texture->baseTexture.sampler));
1950         }
1951     }
1952
1953     unlock_end:
1954     This->Flags &= ~SFLAG_LOCKED;
1955     memset(&This->lockedRect, 0, sizeof(RECT));
1956
1957     /* Overlays have to be redrawn manually after changes with the GL implementation */
1958     if(This->overlay_dest) {
1959         IWineD3DSurface_DrawOverlay(iface);
1960     }
1961     return WINED3D_OK;
1962 }
1963
1964 static void surface_release_client_storage(IWineD3DSurfaceImpl *surface)
1965 {
1966     struct wined3d_context *context;
1967
1968     context = context_acquire(surface->resource.device, NULL);
1969
1970     ENTER_GL();
1971     glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
1972     if (surface->texture_name)
1973     {
1974         surface_bind_and_dirtify(surface, FALSE);
1975         glTexImage2D(surface->texture_target, surface->texture_level,
1976                 GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
1977     }
1978     if (surface->texture_name_srgb)
1979     {
1980         surface_bind_and_dirtify(surface, TRUE);
1981         glTexImage2D(surface->texture_target, surface->texture_level,
1982                 GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
1983     }
1984     glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1985
1986     LEAVE_GL();
1987     context_release(context);
1988
1989     surface_modify_location(surface, SFLAG_INSRGBTEX, FALSE);
1990     surface_modify_location(surface, SFLAG_INTEXTURE, FALSE);
1991     surface_force_reload(surface);
1992 }
1993
1994 static HRESULT WINAPI IWineD3DSurfaceImpl_GetDC(IWineD3DSurface *iface, HDC *pHDC)
1995 {
1996     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1997     WINED3DLOCKED_RECT lock;
1998     HRESULT hr;
1999     RGBQUAD col[256];
2000
2001     TRACE("(%p)->(%p)\n",This,pHDC);
2002
2003     if(This->Flags & SFLAG_USERPTR) {
2004         ERR("Not supported on surfaces with an application-provided surfaces\n");
2005         return WINEDDERR_NODC;
2006     }
2007
2008     /* Give more detailed info for ddraw */
2009     if (This->Flags & SFLAG_DCINUSE)
2010         return WINEDDERR_DCALREADYCREATED;
2011
2012     /* Can't GetDC if the surface is locked */
2013     if (This->Flags & SFLAG_LOCKED)
2014         return WINED3DERR_INVALIDCALL;
2015
2016     memset(&lock, 0, sizeof(lock)); /* To be sure */
2017
2018     /* Create a DIB section if there isn't a hdc yet */
2019     if (!This->hDC)
2020     {
2021         if (This->Flags & SFLAG_CLIENT)
2022         {
2023             surface_load_location(This, SFLAG_INSYSMEM, NULL);
2024             surface_release_client_storage(This);
2025         }
2026         hr = IWineD3DBaseSurfaceImpl_CreateDIBSection(iface);
2027         if(FAILED(hr)) return WINED3DERR_INVALIDCALL;
2028
2029         /* Use the dib section from now on if we are not using a PBO */
2030         if(!(This->Flags & SFLAG_PBO))
2031             This->resource.allocatedMemory = This->dib.bitmap_data;
2032     }
2033
2034     /* Map the surface */
2035     hr = IWineD3DSurface_Map(iface, &lock, NULL, 0);
2036
2037     /* Sync the DIB with the PBO. This can't be done earlier because Map()
2038      * activates the allocatedMemory. */
2039     if (This->Flags & SFLAG_PBO)
2040         memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, This->dib.bitmap_size);
2041
2042     if (FAILED(hr))
2043     {
2044         ERR("IWineD3DSurface_Map failed, hr %#x.\n", hr);
2045         /* keep the dib section */
2046         return hr;
2047     }
2048
2049     if (This->resource.format->id == WINED3DFMT_P8_UINT
2050             || This->resource.format->id == WINED3DFMT_P8_UINT_A8_UNORM)
2051     {
2052         /* GetDC on palettized formats is unsupported in D3D9, and the method is missing in
2053             D3D8, so this should only be used for DX <=7 surfaces (with non-device palettes) */
2054         unsigned int n;
2055         const PALETTEENTRY *pal = NULL;
2056
2057         if(This->palette) {
2058             pal = This->palette->palents;
2059         } else {
2060             IWineD3DSurfaceImpl *dds_primary;
2061             IWineD3DSwapChainImpl *swapchain;
2062             swapchain = (IWineD3DSwapChainImpl *)This->resource.device->swapchains[0];
2063             dds_primary = swapchain->front_buffer;
2064             if (dds_primary && dds_primary->palette)
2065                 pal = dds_primary->palette->palents;
2066         }
2067
2068         if (pal) {
2069             for (n=0; n<256; n++) {
2070                 col[n].rgbRed   = pal[n].peRed;
2071                 col[n].rgbGreen = pal[n].peGreen;
2072                 col[n].rgbBlue  = pal[n].peBlue;
2073                 col[n].rgbReserved = 0;
2074             }
2075             SetDIBColorTable(This->hDC, 0, 256, col);
2076         }
2077     }
2078
2079     *pHDC = This->hDC;
2080     TRACE("returning %p\n",*pHDC);
2081     This->Flags |= SFLAG_DCINUSE;
2082
2083     return WINED3D_OK;
2084 }
2085
2086 static HRESULT WINAPI IWineD3DSurfaceImpl_ReleaseDC(IWineD3DSurface *iface, HDC hDC)
2087 {
2088     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2089
2090     TRACE("(%p)->(%p)\n",This,hDC);
2091
2092     if (!(This->Flags & SFLAG_DCINUSE))
2093         return WINEDDERR_NODC;
2094
2095     if (This->hDC !=hDC) {
2096         WARN("Application tries to release an invalid DC(%p), surface dc is %p\n", hDC, This->hDC);
2097         return WINEDDERR_NODC;
2098     }
2099
2100     if((This->Flags & SFLAG_PBO) && This->resource.allocatedMemory) {
2101         /* Copy the contents of the DIB over to the PBO */
2102         memcpy(This->resource.allocatedMemory, This->dib.bitmap_data, This->dib.bitmap_size);
2103     }
2104
2105     /* we locked first, so unlock now */
2106     IWineD3DSurface_Unmap(iface);
2107
2108     This->Flags &= ~SFLAG_DCINUSE;
2109
2110     return WINED3D_OK;
2111 }
2112
2113 /* ******************************************************
2114    IWineD3DSurface Internal (No mapping to directx api) parts follow
2115    ****************************************************** */
2116
2117 HRESULT d3dfmt_get_conv(IWineD3DSurfaceImpl *This, BOOL need_alpha_ck,
2118         BOOL use_texturing, struct wined3d_format *format, CONVERT_TYPES *convert)
2119 {
2120     BOOL colorkey_active = need_alpha_ck && (This->CKeyFlags & WINEDDSD_CKSRCBLT);
2121     IWineD3DDeviceImpl *device = This->resource.device;
2122     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2123     BOOL blit_supported = FALSE;
2124
2125     /* Copy the default values from the surface. Below we might perform fixups */
2126     /* TODO: get rid of color keying desc fixups by using e.g. a table. */
2127     *format = *This->resource.format;
2128     *convert = NO_CONVERSION;
2129
2130     /* Ok, now look if we have to do any conversion */
2131     switch (This->resource.format->id)
2132     {
2133         case WINED3DFMT_P8_UINT:
2134             /* Below the call to blit_supported is disabled for Wine 1.2
2135              * because the function isn't operating correctly yet. At the
2136              * moment 8-bit blits are handled in software and if certain GL
2137              * extensions are around, surface conversion is performed at
2138              * upload time. The blit_supported call recognizes it as a
2139              * destination fixup. This type of upload 'fixup' and 8-bit to
2140              * 8-bit blits need to be handled by the blit_shader.
2141              * TODO: get rid of this #if 0. */
2142 #if 0
2143             blit_supported = device->blitter->blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
2144                     &rect, This->resource.usage, This->resource.pool, This->resource.format,
2145                     &rect, This->resource.usage, This->resource.pool, This->resource.format);
2146 #endif
2147             blit_supported = gl_info->supported[EXT_PALETTED_TEXTURE] || gl_info->supported[ARB_FRAGMENT_PROGRAM];
2148
2149             /* Use conversion when the blit_shader backend supports it. It only supports this in case of
2150              * texturing. Further also use conversion in case of color keying.
2151              * Paletted textures can be emulated using shaders but only do that for 2D purposes e.g. situations
2152              * in which the main render target uses p8. Some games like GTA Vice City use P8 for texturing which
2153              * conflicts with this.
2154              */
2155             if (!((blit_supported && device->render_targets && This == device->render_targets[0]))
2156                     || colorkey_active || !use_texturing)
2157             {
2158                 format->glFormat = GL_RGBA;
2159                 format->glInternal = GL_RGBA;
2160                 format->glType = GL_UNSIGNED_BYTE;
2161                 format->conv_byte_count = 4;
2162                 if (colorkey_active)
2163                     *convert = CONVERT_PALETTED_CK;
2164                 else
2165                     *convert = CONVERT_PALETTED;
2166             }
2167             break;
2168
2169         case WINED3DFMT_B2G3R3_UNORM:
2170             /* **********************
2171                 GL_UNSIGNED_BYTE_3_3_2
2172                 ********************** */
2173             if (colorkey_active) {
2174                 /* This texture format will never be used.. So do not care about color keying
2175                     up until the point in time it will be needed :-) */
2176                 FIXME(" ColorKeying not supported in the RGB 332 format !\n");
2177             }
2178             break;
2179
2180         case WINED3DFMT_B5G6R5_UNORM:
2181             if (colorkey_active)
2182             {
2183                 *convert = CONVERT_CK_565;
2184                 format->glFormat = GL_RGBA;
2185                 format->glInternal = GL_RGB5_A1;
2186                 format->glType = GL_UNSIGNED_SHORT_5_5_5_1;
2187                 format->conv_byte_count = 2;
2188             }
2189             break;
2190
2191         case WINED3DFMT_B5G5R5X1_UNORM:
2192             if (colorkey_active)
2193             {
2194                 *convert = CONVERT_CK_5551;
2195                 format->glFormat = GL_BGRA;
2196                 format->glInternal = GL_RGB5_A1;
2197                 format->glType = GL_UNSIGNED_SHORT_1_5_5_5_REV;
2198                 format->conv_byte_count = 2;
2199             }
2200             break;
2201
2202         case WINED3DFMT_B8G8R8_UNORM:
2203             if (colorkey_active)
2204             {
2205                 *convert = CONVERT_CK_RGB24;
2206                 format->glFormat = GL_RGBA;
2207                 format->glInternal = GL_RGBA8;
2208                 format->glType = GL_UNSIGNED_INT_8_8_8_8;
2209                 format->conv_byte_count = 4;
2210             }
2211             break;
2212
2213         case WINED3DFMT_B8G8R8X8_UNORM:
2214             if (colorkey_active)
2215             {
2216                 *convert = CONVERT_RGB32_888;
2217                 format->glFormat = GL_RGBA;
2218                 format->glInternal = GL_RGBA8;
2219                 format->glType = GL_UNSIGNED_INT_8_8_8_8;
2220                 format->conv_byte_count = 4;
2221             }
2222             break;
2223
2224         default:
2225             break;
2226     }
2227
2228     return WINED3D_OK;
2229 }
2230
2231 void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey)
2232 {
2233     IWineD3DDeviceImpl *device = This->resource.device;
2234     IWineD3DPaletteImpl *pal = This->palette;
2235     BOOL index_in_alpha = FALSE;
2236     unsigned int i;
2237
2238     /* Old games like StarCraft, C&C, Red Alert and others use P8 render targets.
2239      * Reading back the RGB output each lockrect (each frame as they lock the whole screen)
2240      * is slow. Further RGB->P8 conversion is not possible because palettes can have
2241      * duplicate entries. Store the color key in the unused alpha component to speed the
2242      * download up and to make conversion unneeded. */
2243     index_in_alpha = primary_render_target_is_p8(device);
2244
2245     if (!pal)
2246     {
2247         UINT dxVersion = ((IWineD3DImpl *)device->wined3d)->dxVersion;
2248
2249         /* In DirectDraw the palette is a property of the surface, there are no such things as device palettes. */
2250         if (dxVersion <= 7)
2251         {
2252             ERR("This code should never get entered for DirectDraw!, expect problems\n");
2253             if (index_in_alpha)
2254             {
2255                 /* Guarantees that memory representation remains correct after sysmem<->texture transfers even if
2256                  * there's no palette at this time. */
2257                 for (i = 0; i < 256; i++) table[i][3] = i;
2258             }
2259         }
2260         else
2261         {
2262             /* Direct3D >= 8 palette usage style: P8 textures use device palettes, palette entry format is A8R8G8B8,
2263              * alpha is stored in peFlags and may be used by the app if D3DPTEXTURECAPS_ALPHAPALETTE device
2264              * capability flag is present (wine does advertise this capability) */
2265             for (i = 0; i < 256; ++i)
2266             {
2267                 table[i][0] = device->palettes[device->currentPalette][i].peRed;
2268                 table[i][1] = device->palettes[device->currentPalette][i].peGreen;
2269                 table[i][2] = device->palettes[device->currentPalette][i].peBlue;
2270                 table[i][3] = device->palettes[device->currentPalette][i].peFlags;
2271             }
2272         }
2273     }
2274     else
2275     {
2276         TRACE("Using surface palette %p\n", pal);
2277         /* Get the surface's palette */
2278         for (i = 0; i < 256; ++i)
2279         {
2280             table[i][0] = pal->palents[i].peRed;
2281             table[i][1] = pal->palents[i].peGreen;
2282             table[i][2] = pal->palents[i].peBlue;
2283
2284             /* When index_in_alpha is set the palette index is stored in the
2285              * alpha component. In case of a readback we can then read
2286              * GL_ALPHA. Color keying is handled in BltOverride using a
2287              * GL_ALPHA_TEST using GL_NOT_EQUAL. In case of index_in_alpha the
2288              * color key itself is passed to glAlphaFunc in other cases the
2289              * alpha component of pixels that should be masked away is set to 0. */
2290             if (index_in_alpha)
2291             {
2292                 table[i][3] = i;
2293             }
2294             else if (colorkey && (i >= This->SrcBltCKey.dwColorSpaceLowValue)
2295                     && (i <= This->SrcBltCKey.dwColorSpaceHighValue))
2296             {
2297                 table[i][3] = 0x00;
2298             }
2299             else if(pal->Flags & WINEDDPCAPS_ALPHA)
2300             {
2301                 table[i][3] = pal->palents[i].peFlags;
2302             }
2303             else
2304             {
2305                 table[i][3] = 0xFF;
2306             }
2307         }
2308     }
2309 }
2310
2311 static HRESULT d3dfmt_convert_surface(const BYTE *src, BYTE *dst, UINT pitch, UINT width,
2312         UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *This)
2313 {
2314     const BYTE *source;
2315     BYTE *dest;
2316     TRACE("(%p)->(%p),(%d,%d,%d,%d,%p)\n", src, dst, pitch, height, outpitch, convert,This);
2317
2318     switch (convert) {
2319         case NO_CONVERSION:
2320         {
2321             memcpy(dst, src, pitch * height);
2322             break;
2323         }
2324         case CONVERT_PALETTED:
2325         case CONVERT_PALETTED_CK:
2326         {
2327             BYTE table[256][4];
2328             unsigned int x, y;
2329
2330             d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
2331
2332             for (y = 0; y < height; y++)
2333             {
2334                 source = src + pitch * y;
2335                 dest = dst + outpitch * y;
2336                 /* This is an 1 bpp format, using the width here is fine */
2337                 for (x = 0; x < width; x++) {
2338                     BYTE color = *source++;
2339                     *dest++ = table[color][0];
2340                     *dest++ = table[color][1];
2341                     *dest++ = table[color][2];
2342                     *dest++ = table[color][3];
2343                 }
2344             }
2345         }
2346         break;
2347
2348         case CONVERT_CK_565:
2349         {
2350             /* Converting the 565 format in 5551 packed to emulate color-keying.
2351
2352               Note : in all these conversion, it would be best to average the averaging
2353                       pixels to get the color of the pixel that will be color-keyed to
2354                       prevent 'color bleeding'. This will be done later on if ever it is
2355                       too visible.
2356
2357               Note2: Nvidia documents say that their driver does not support alpha + color keying
2358                      on the same surface and disables color keying in such a case
2359             */
2360             unsigned int x, y;
2361             const WORD *Source;
2362             WORD *Dest;
2363
2364             TRACE("Color keyed 565\n");
2365
2366             for (y = 0; y < height; y++) {
2367                 Source = (const WORD *)(src + y * pitch);
2368                 Dest = (WORD *) (dst + y * outpitch);
2369                 for (x = 0; x < width; x++ ) {
2370                     WORD color = *Source++;
2371                     *Dest = ((color & 0xFFC0) | ((color & 0x1F) << 1));
2372                     if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2373                         (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2374                         *Dest |= 0x0001;
2375                     }
2376                     Dest++;
2377                 }
2378             }
2379         }
2380         break;
2381
2382         case CONVERT_CK_5551:
2383         {
2384             /* Converting X1R5G5B5 format to R5G5B5A1 to emulate color-keying. */
2385             unsigned int x, y;
2386             const WORD *Source;
2387             WORD *Dest;
2388             TRACE("Color keyed 5551\n");
2389             for (y = 0; y < height; y++) {
2390                 Source = (const WORD *)(src + y * pitch);
2391                 Dest = (WORD *) (dst + y * outpitch);
2392                 for (x = 0; x < width; x++ ) {
2393                     WORD color = *Source++;
2394                     *Dest = color;
2395                     if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2396                         (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2397                         *Dest |= (1 << 15);
2398                     }
2399                     else {
2400                         *Dest &= ~(1 << 15);
2401                     }
2402                     Dest++;
2403                 }
2404             }
2405         }
2406         break;
2407
2408         case CONVERT_CK_RGB24:
2409         {
2410             /* Converting R8G8B8 format to R8G8B8A8 with color-keying. */
2411             unsigned int x, y;
2412             for (y = 0; y < height; y++)
2413             {
2414                 source = src + pitch * y;
2415                 dest = dst + outpitch * y;
2416                 for (x = 0; x < width; x++) {
2417                     DWORD color = ((DWORD)source[0] << 16) + ((DWORD)source[1] << 8) + (DWORD)source[2] ;
2418                     DWORD dstcolor = color << 8;
2419                     if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2420                         (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2421                         dstcolor |= 0xff;
2422                     }
2423                     *(DWORD*)dest = dstcolor;
2424                     source += 3;
2425                     dest += 4;
2426                 }
2427             }
2428         }
2429         break;
2430
2431         case CONVERT_RGB32_888:
2432         {
2433             /* Converting X8R8G8B8 format to R8G8B8A8 with color-keying. */
2434             unsigned int x, y;
2435             for (y = 0; y < height; y++)
2436             {
2437                 source = src + pitch * y;
2438                 dest = dst + outpitch * y;
2439                 for (x = 0; x < width; x++) {
2440                     DWORD color = 0xffffff & *(const DWORD*)source;
2441                     DWORD dstcolor = color << 8;
2442                     if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2443                         (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2444                         dstcolor |= 0xff;
2445                     }
2446                     *(DWORD*)dest = dstcolor;
2447                     source += 4;
2448                     dest += 4;
2449                 }
2450             }
2451         }
2452         break;
2453
2454         default:
2455             ERR("Unsupported conversion type %#x.\n", convert);
2456     }
2457     return WINED3D_OK;
2458 }
2459
2460 BOOL palette9_changed(IWineD3DSurfaceImpl *This)
2461 {
2462     IWineD3DDeviceImpl *device = This->resource.device;
2463
2464     if (This->palette || (This->resource.format->id != WINED3DFMT_P8_UINT
2465             && This->resource.format->id != WINED3DFMT_P8_UINT_A8_UNORM))
2466     {
2467         /* If a ddraw-style palette is attached assume no d3d9 palette change.
2468          * Also the palette isn't interesting if the surface format isn't P8 or A8P8
2469          */
2470         return FALSE;
2471     }
2472
2473     if (This->palette9)
2474     {
2475         if (!memcmp(This->palette9, device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256))
2476         {
2477             return FALSE;
2478         }
2479     } else {
2480         This->palette9 = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
2481     }
2482     memcpy(This->palette9, device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256);
2483     return TRUE;
2484 }
2485
2486 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadTexture(IWineD3DSurface *iface, BOOL srgb_mode) {
2487     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2488     DWORD flag = srgb_mode ? SFLAG_INSRGBTEX : SFLAG_INTEXTURE;
2489
2490     TRACE("iface %p, srgb %#x.\n", iface, srgb_mode);
2491
2492     if (!(This->Flags & flag)) {
2493         TRACE("Reloading because surface is dirty\n");
2494     } else if(/* Reload: gl texture has ck, now no ckey is set OR */
2495               ((This->Flags & SFLAG_GLCKEY) && (!(This->CKeyFlags & WINEDDSD_CKSRCBLT))) ||
2496               /* Reload: vice versa  OR */
2497               ((!(This->Flags & SFLAG_GLCKEY)) && (This->CKeyFlags & WINEDDSD_CKSRCBLT)) ||
2498               /* Also reload: Color key is active AND the color key has changed */
2499               ((This->CKeyFlags & WINEDDSD_CKSRCBLT) && (
2500                 (This->glCKey.dwColorSpaceLowValue != This->SrcBltCKey.dwColorSpaceLowValue) ||
2501                 (This->glCKey.dwColorSpaceHighValue != This->SrcBltCKey.dwColorSpaceHighValue)))) {
2502         TRACE("Reloading because of color keying\n");
2503         /* To perform the color key conversion we need a sysmem copy of
2504          * the surface. Make sure we have it
2505          */
2506
2507         surface_load_location(This, SFLAG_INSYSMEM, NULL);
2508         /* Make sure the texture is reloaded because of the color key change, this kills performance though :( */
2509         /* TODO: This is not necessarily needed with hw palettized texture support */
2510         surface_modify_location(This, SFLAG_INSYSMEM, TRUE);
2511     } else {
2512         TRACE("surface is already in texture\n");
2513         return WINED3D_OK;
2514     }
2515
2516     /* Resources are placed in system RAM and do not need to be recreated when a device is lost.
2517      *  These resources are not bound by device size or format restrictions. Because of this,
2518      *  these resources cannot be accessed by the Direct3D device nor set as textures or render targets.
2519      *  However, these resources can always be created, locked, and copied.
2520      */
2521     if (This->resource.pool == WINED3DPOOL_SCRATCH )
2522     {
2523         FIXME("(%p) Operation not supported for scratch textures\n",This);
2524         return WINED3DERR_INVALIDCALL;
2525     }
2526
2527     surface_load_location(This, flag, NULL /* no partial locking for textures yet */);
2528
2529     if (!(This->Flags & SFLAG_DONOTFREE)) {
2530         HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
2531         This->resource.allocatedMemory = NULL;
2532         This->resource.heapMemory = NULL;
2533         surface_modify_location(This, SFLAG_INSYSMEM, FALSE);
2534     }
2535
2536     return WINED3D_OK;
2537 }
2538
2539 /* Context activation is done by the caller. */
2540 static void WINAPI IWineD3DSurfaceImpl_BindTexture(IWineD3DSurface *iface, BOOL srgb)
2541 {
2542     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2543
2544     TRACE("iface %p, srgb %#x.\n", iface, srgb);
2545
2546     if (This->container.type == WINED3D_CONTAINER_TEXTURE)
2547     {
2548         TRACE("Passing to container.\n");
2549         IWineD3DBaseTexture_BindTexture((IWineD3DBaseTexture *)This->container.u.texture, srgb);
2550     }
2551     else
2552     {
2553         GLuint *name;
2554
2555         TRACE("(%p) : Binding surface\n", This);
2556
2557         name = srgb ? &This->texture_name_srgb : &This->texture_name;
2558
2559         ENTER_GL();
2560
2561         if (!This->texture_level)
2562         {
2563             if (!*name) {
2564                 glGenTextures(1, name);
2565                 checkGLcall("glGenTextures");
2566                 TRACE("Surface %p given name %d\n", This, *name);
2567
2568                 glBindTexture(This->texture_target, *name);
2569                 checkGLcall("glBindTexture");
2570                 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2571                 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)");
2572                 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2573                 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)");
2574                 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
2575                 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)");
2576                 glTexParameteri(This->texture_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2577                 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_MIN_FILTER, GL_NEAREST)");
2578                 glTexParameteri(This->texture_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2579                 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_MAG_FILTER, GL_NEAREST)");
2580             }
2581             /* This is where we should be reducing the amount of GLMemoryUsed */
2582         } else if (*name) {
2583             /* Mipmap surfaces should have a base texture container */
2584             ERR("Mipmap surface has a glTexture bound to it!\n");
2585         }
2586
2587         glBindTexture(This->texture_target, *name);
2588         checkGLcall("glBindTexture");
2589
2590         LEAVE_GL();
2591     }
2592 }
2593
2594 static HRESULT WINAPI IWineD3DSurfaceImpl_SetFormat(IWineD3DSurface *iface, enum wined3d_format_id format)
2595 {
2596     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2597     HRESULT hr;
2598
2599     TRACE("(%p) : Calling base function first\n", This);
2600     hr = IWineD3DBaseSurfaceImpl_SetFormat(iface, format);
2601     if(SUCCEEDED(hr)) {
2602         This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
2603         TRACE("(%p) : glFormat %d, glFormatInternal %d, glType %d\n", This, This->resource.format->glFormat,
2604                 This->resource.format->glInternal, This->resource.format->glType);
2605     }
2606     return hr;
2607 }
2608
2609 static HRESULT WINAPI IWineD3DSurfaceImpl_SetMem(IWineD3DSurface *iface, void *Mem) {
2610     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
2611
2612     if(This->Flags & (SFLAG_LOCKED | SFLAG_DCINUSE)) {
2613         WARN("Surface is locked or the HDC is in use\n");
2614         return WINED3DERR_INVALIDCALL;
2615     }
2616
2617     if(Mem && Mem != This->resource.allocatedMemory) {
2618         void *release = NULL;
2619
2620         /* Do I have to copy the old surface content? */
2621         if(This->Flags & SFLAG_DIBSECTION) {
2622                 /* Release the DC. No need to hold the critical section for the update
2623                  * Thread because this thread runs only on front buffers, but this method
2624                  * fails for render targets in the check above.
2625                  */
2626                 SelectObject(This->hDC, This->dib.holdbitmap);
2627                 DeleteDC(This->hDC);
2628                 /* Release the DIB section */
2629                 DeleteObject(This->dib.DIBsection);
2630                 This->dib.bitmap_data = NULL;
2631                 This->resource.allocatedMemory = NULL;
2632                 This->hDC = NULL;
2633                 This->Flags &= ~SFLAG_DIBSECTION;
2634         } else if(!(This->Flags & SFLAG_USERPTR)) {
2635             release = This->resource.heapMemory;
2636             This->resource.heapMemory = NULL;
2637         }
2638         This->resource.allocatedMemory = Mem;
2639         This->Flags |= SFLAG_USERPTR | SFLAG_INSYSMEM;
2640
2641         /* Now the surface memory is most up do date. Invalidate drawable and texture */
2642         surface_modify_location(This, SFLAG_INSYSMEM, TRUE);
2643
2644         /* For client textures opengl has to be notified */
2645         if (This->Flags & SFLAG_CLIENT)
2646             surface_release_client_storage(This);
2647
2648         /* Now free the old memory if any */
2649         HeapFree(GetProcessHeap(), 0, release);
2650     }
2651     else if (This->Flags & SFLAG_USERPTR)
2652     {
2653         /* Map and GetDC will re-create the dib section and allocated memory. */
2654         This->resource.allocatedMemory = NULL;
2655         /* HeapMemory should be NULL already */
2656         if (This->resource.heapMemory)
2657             ERR("User pointer surface has heap memory allocated.\n");
2658         This->Flags &= ~SFLAG_USERPTR;
2659
2660         if (This->Flags & SFLAG_CLIENT)
2661             surface_release_client_storage(This);
2662     }
2663     return WINED3D_OK;
2664 }
2665
2666 void flip_surface(IWineD3DSurfaceImpl *front, IWineD3DSurfaceImpl *back) {
2667
2668     /* Flip the surface contents */
2669     /* Flip the DC */
2670     {
2671         HDC tmp;
2672         tmp = front->hDC;
2673         front->hDC = back->hDC;
2674         back->hDC = tmp;
2675     }
2676
2677     /* Flip the DIBsection */
2678     {
2679         HBITMAP tmp;
2680         BOOL hasDib = front->Flags & SFLAG_DIBSECTION;
2681         tmp = front->dib.DIBsection;
2682         front->dib.DIBsection = back->dib.DIBsection;
2683         back->dib.DIBsection = tmp;
2684
2685         if(back->Flags & SFLAG_DIBSECTION) front->Flags |= SFLAG_DIBSECTION;
2686         else front->Flags &= ~SFLAG_DIBSECTION;
2687         if(hasDib) back->Flags |= SFLAG_DIBSECTION;
2688         else back->Flags &= ~SFLAG_DIBSECTION;
2689     }
2690
2691     /* Flip the surface data */
2692     {
2693         void* tmp;
2694
2695         tmp = front->dib.bitmap_data;
2696         front->dib.bitmap_data = back->dib.bitmap_data;
2697         back->dib.bitmap_data = tmp;
2698
2699         tmp = front->resource.allocatedMemory;
2700         front->resource.allocatedMemory = back->resource.allocatedMemory;
2701         back->resource.allocatedMemory = tmp;
2702
2703         tmp = front->resource.heapMemory;
2704         front->resource.heapMemory = back->resource.heapMemory;
2705         back->resource.heapMemory = tmp;
2706     }
2707
2708     /* Flip the PBO */
2709     {
2710         GLuint tmp_pbo = front->pbo;
2711         front->pbo = back->pbo;
2712         back->pbo = tmp_pbo;
2713     }
2714
2715     /* client_memory should not be different, but just in case */
2716     {
2717         BOOL tmp;
2718         tmp = front->dib.client_memory;
2719         front->dib.client_memory = back->dib.client_memory;
2720         back->dib.client_memory = tmp;
2721     }
2722
2723     /* Flip the opengl texture */
2724     {
2725         GLuint tmp;
2726
2727         tmp = back->texture_name;
2728         back->texture_name = front->texture_name;
2729         front->texture_name = tmp;
2730
2731         tmp = back->texture_name_srgb;
2732         back->texture_name_srgb = front->texture_name_srgb;
2733         front->texture_name_srgb = tmp;
2734     }
2735
2736     {
2737         DWORD tmp_flags = back->Flags;
2738         back->Flags = front->Flags;
2739         front->Flags = tmp_flags;
2740     }
2741 }
2742
2743 static HRESULT WINAPI IWineD3DSurfaceImpl_Flip(IWineD3DSurface *iface, IWineD3DSurface *override, DWORD Flags) {
2744     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2745     IWineD3DSwapChainImpl *swapchain = NULL;
2746
2747     TRACE("(%p)->(%p,%x)\n", This, override, Flags);
2748
2749     /* Flipping is only supported on RenderTargets and overlays*/
2750     if( !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_OVERLAY)) ) {
2751         WARN("Tried to flip a non-render target, non-overlay surface\n");
2752         return WINEDDERR_NOTFLIPPABLE;
2753     }
2754
2755     if(This->resource.usage & WINED3DUSAGE_OVERLAY) {
2756         flip_surface(This, (IWineD3DSurfaceImpl *) override);
2757
2758         /* Update the overlay if it is visible */
2759         if(This->overlay_dest) {
2760             return IWineD3DSurface_DrawOverlay((IWineD3DSurface *) This);
2761         } else {
2762             return WINED3D_OK;
2763         }
2764     }
2765
2766     if(override) {
2767         /* DDraw sets this for the X11 surfaces, so don't confuse the user
2768          * FIXME("(%p) Target override is not supported by now\n", This);
2769          * Additionally, it isn't really possible to support triple-buffering
2770          * properly on opengl at all
2771          */
2772     }
2773
2774     if (This->container.type != WINED3D_CONTAINER_SWAPCHAIN)
2775     {
2776         ERR("Flipped surface is not on a swapchain\n");
2777         return WINEDDERR_NOTFLIPPABLE;
2778     }
2779     swapchain = This->container.u.swapchain;
2780
2781     /* Just overwrite the swapchain presentation interval. This is ok because only ddraw apps can call Flip,
2782      * and only d3d8 and d3d9 apps specify the presentation interval
2783      */
2784     if (!(Flags & (WINEDDFLIP_NOVSYNC | WINEDDFLIP_INTERVAL2 | WINEDDFLIP_INTERVAL3 | WINEDDFLIP_INTERVAL4)))
2785     {
2786         /* Most common case first to avoid wasting time on all the other cases */
2787         swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_ONE;
2788     } else if(Flags & WINEDDFLIP_NOVSYNC) {
2789         swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
2790     } else if(Flags & WINEDDFLIP_INTERVAL2) {
2791         swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_TWO;
2792     } else if(Flags & WINEDDFLIP_INTERVAL3) {
2793         swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_THREE;
2794     } else {
2795         swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_FOUR;
2796     }
2797
2798     /* Flipping a OpenGL surface -> Use WineD3DDevice::Present */
2799     return IWineD3DSwapChain_Present((IWineD3DSwapChain *)swapchain,
2800             NULL, NULL, swapchain->win_handle, NULL, 0);
2801 }
2802
2803 /* Does a direct frame buffer -> texture copy. Stretching is done
2804  * with single pixel copy calls
2805  */
2806 static void fb_copy_to_texture_direct(IWineD3DSurfaceImpl *dst_surface, IWineD3DSurfaceImpl *src_surface,
2807         const RECT *src_rect, const RECT *dst_rect_in, WINED3DTEXTUREFILTERTYPE Filter)
2808 {
2809     IWineD3DDeviceImpl *device = dst_surface->resource.device;
2810     float xrel, yrel;
2811     UINT row;
2812     struct wined3d_context *context;
2813     BOOL upsidedown = FALSE;
2814     RECT dst_rect = *dst_rect_in;
2815
2816     /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
2817      * glCopyTexSubImage is a bit picky about the parameters we pass to it
2818      */
2819     if(dst_rect.top > dst_rect.bottom) {
2820         UINT tmp = dst_rect.bottom;
2821         dst_rect.bottom = dst_rect.top;
2822         dst_rect.top = tmp;
2823         upsidedown = TRUE;
2824     }
2825
2826     context = context_acquire(device, src_surface);
2827     context_apply_blit_state(context, device);
2828     surface_internal_preload(dst_surface, SRGB_RGB);
2829     ENTER_GL();
2830
2831     /* Bind the target texture */
2832     glBindTexture(dst_surface->texture_target, dst_surface->texture_name);
2833     checkGLcall("glBindTexture");
2834     if (surface_is_offscreen(src_surface))
2835     {
2836         TRACE("Reading from an offscreen target\n");
2837         upsidedown = !upsidedown;
2838         glReadBuffer(device->offscreenBuffer);
2839     }
2840     else
2841     {
2842         glReadBuffer(surface_get_gl_buffer(src_surface));
2843     }
2844     checkGLcall("glReadBuffer");
2845
2846     xrel = (float) (src_rect->right - src_rect->left) / (float) (dst_rect.right - dst_rect.left);
2847     yrel = (float) (src_rect->bottom - src_rect->top) / (float) (dst_rect.bottom - dst_rect.top);
2848
2849     if ((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
2850     {
2851         FIXME("Doing a pixel by pixel copy from the framebuffer to a texture, expect major performance issues\n");
2852
2853         if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
2854             ERR("Texture filtering not supported in direct blit\n");
2855         }
2856     }
2857     else if ((Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT)
2858             && ((yrel - 1.0f < -eps) || (yrel - 1.0f > eps)))
2859     {
2860         ERR("Texture filtering not supported in direct blit\n");
2861     }
2862
2863     if (upsidedown
2864             && !((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
2865             && !((yrel - 1.0f < -eps) || (yrel - 1.0f > eps)))
2866     {
2867         /* Upside down copy without stretching is nice, one glCopyTexSubImage call will do */
2868
2869         glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
2870                 dst_rect.left /*xoffset */, dst_rect.top /* y offset */,
2871                 src_rect->left, src_surface->currentDesc.Height - src_rect->bottom,
2872                 dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top);
2873     } else {
2874         UINT yoffset = src_surface->currentDesc.Height - src_rect->top + dst_rect.top - 1;
2875         /* I have to process this row by row to swap the image,
2876          * otherwise it would be upside down, so stretching in y direction
2877          * doesn't cost extra time
2878          *
2879          * However, stretching in x direction can be avoided if not necessary
2880          */
2881         for(row = dst_rect.top; row < dst_rect.bottom; row++) {
2882             if ((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
2883             {
2884                 /* Well, that stuff works, but it's very slow.
2885                  * find a better way instead
2886                  */
2887                 UINT col;
2888
2889                 for (col = dst_rect.left; col < dst_rect.right; ++col)
2890                 {
2891                     glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
2892                             dst_rect.left + col /* x offset */, row /* y offset */,
2893                             src_rect->left + col * xrel, yoffset - (int) (row * yrel), 1, 1);
2894                 }
2895             }
2896             else
2897             {
2898                 glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
2899                         dst_rect.left /* x offset */, row /* y offset */,
2900                         src_rect->left, yoffset - (int) (row * yrel), dst_rect.right - dst_rect.left, 1);
2901             }
2902         }
2903     }
2904     checkGLcall("glCopyTexSubImage2D");
2905
2906     LEAVE_GL();
2907     context_release(context);
2908
2909     /* The texture is now most up to date - If the surface is a render target and has a drawable, this
2910      * path is never entered
2911      */
2912     surface_modify_location(dst_surface, SFLAG_INTEXTURE, TRUE);
2913 }
2914
2915 /* Uses the hardware to stretch and flip the image */
2916 static void fb_copy_to_texture_hwstretch(IWineD3DSurfaceImpl *dst_surface, IWineD3DSurfaceImpl *src_surface,
2917         const RECT *src_rect, const RECT *dst_rect_in, WINED3DTEXTUREFILTERTYPE Filter)
2918 {
2919     IWineD3DDeviceImpl *device = dst_surface->resource.device;
2920     GLuint src, backup = 0;
2921     IWineD3DSwapChainImpl *src_swapchain = NULL;
2922     float left, right, top, bottom; /* Texture coordinates */
2923     UINT fbwidth = src_surface->currentDesc.Width;
2924     UINT fbheight = src_surface->currentDesc.Height;
2925     struct wined3d_context *context;
2926     GLenum drawBuffer = GL_BACK;
2927     GLenum texture_target;
2928     BOOL noBackBufferBackup;
2929     BOOL src_offscreen;
2930     BOOL upsidedown = FALSE;
2931     RECT dst_rect = *dst_rect_in;
2932
2933     TRACE("Using hwstretch blit\n");
2934     /* Activate the Proper context for reading from the source surface, set it up for blitting */
2935     context = context_acquire(device, src_surface);
2936     context_apply_blit_state(context, device);
2937     surface_internal_preload(dst_surface, SRGB_RGB);
2938
2939     src_offscreen = surface_is_offscreen(src_surface);
2940     noBackBufferBackup = src_offscreen && wined3d_settings.offscreen_rendering_mode == ORM_FBO;
2941     if (!noBackBufferBackup && !src_surface->texture_name)
2942     {
2943         /* Get it a description */
2944         surface_internal_preload(src_surface, SRGB_RGB);
2945     }
2946     ENTER_GL();
2947
2948     /* Try to use an aux buffer for drawing the rectangle. This way it doesn't need restoring.
2949      * This way we don't have to wait for the 2nd readback to finish to leave this function.
2950      */
2951     if (context->aux_buffers >= 2)
2952     {
2953         /* Got more than one aux buffer? Use the 2nd aux buffer */
2954         drawBuffer = GL_AUX1;
2955     }
2956     else if ((!src_offscreen || device->offscreenBuffer == GL_BACK) && context->aux_buffers >= 1)
2957     {
2958         /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
2959         drawBuffer = GL_AUX0;
2960     }
2961
2962     if(noBackBufferBackup) {
2963         glGenTextures(1, &backup);
2964         checkGLcall("glGenTextures");
2965         glBindTexture(GL_TEXTURE_2D, backup);
2966         checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
2967         texture_target = GL_TEXTURE_2D;
2968     } else {
2969         /* Backup the back buffer and copy the source buffer into a texture to draw an upside down stretched quad. If
2970          * we are reading from the back buffer, the backup can be used as source texture
2971          */
2972         texture_target = src_surface->texture_target;
2973         glBindTexture(texture_target, src_surface->texture_name);
2974         checkGLcall("glBindTexture(texture_target, src_surface->texture_name)");
2975         glEnable(texture_target);
2976         checkGLcall("glEnable(texture_target)");
2977
2978         /* For now invalidate the texture copy of the back buffer. Drawable and sysmem copy are untouched */
2979         src_surface->Flags &= ~SFLAG_INTEXTURE;
2980     }
2981
2982     /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
2983      * glCopyTexSubImage is a bit picky about the parameters we pass to it
2984      */
2985     if(dst_rect.top > dst_rect.bottom) {
2986         UINT tmp = dst_rect.bottom;
2987         dst_rect.bottom = dst_rect.top;
2988         dst_rect.top = tmp;
2989         upsidedown = TRUE;
2990     }
2991
2992     if (src_offscreen)
2993     {
2994         TRACE("Reading from an offscreen target\n");
2995         upsidedown = !upsidedown;
2996         glReadBuffer(device->offscreenBuffer);
2997     }
2998     else
2999     {
3000         glReadBuffer(surface_get_gl_buffer(src_surface));
3001     }
3002
3003     /* TODO: Only back up the part that will be overwritten */
3004     glCopyTexSubImage2D(texture_target, 0,
3005                         0, 0 /* read offsets */,
3006                         0, 0,
3007                         fbwidth,
3008                         fbheight);
3009
3010     checkGLcall("glCopyTexSubImage2D");
3011
3012     /* No issue with overriding these - the sampler is dirty due to blit usage */
3013     glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER,
3014             wined3d_gl_mag_filter(magLookup, Filter));
3015     checkGLcall("glTexParameteri");
3016     glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER,
3017             wined3d_gl_min_mip_filter(minMipLookup, Filter, WINED3DTEXF_NONE));
3018     checkGLcall("glTexParameteri");
3019
3020     if (src_surface->container.type == WINED3D_CONTAINER_SWAPCHAIN)
3021         src_swapchain = src_surface->container.u.swapchain;
3022     if (!src_swapchain || src_surface == src_swapchain->back_buffers[0])
3023     {
3024         src = backup ? backup : src_surface->texture_name;
3025     }
3026     else
3027     {
3028         glReadBuffer(GL_FRONT);
3029         checkGLcall("glReadBuffer(GL_FRONT)");
3030
3031         glGenTextures(1, &src);
3032         checkGLcall("glGenTextures(1, &src)");
3033         glBindTexture(GL_TEXTURE_2D, src);
3034         checkGLcall("glBindTexture(GL_TEXTURE_2D, src)");
3035
3036         /* TODO: Only copy the part that will be read. Use src_rect->left, src_rect->bottom as origin, but with the width watch
3037          * out for power of 2 sizes
3038          */
3039         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, src_surface->pow2Width,
3040                 src_surface->pow2Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
3041         checkGLcall("glTexImage2D");
3042         glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
3043                             0, 0 /* read offsets */,
3044                             0, 0,
3045                             fbwidth,
3046                             fbheight);
3047
3048         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
3049         checkGLcall("glTexParameteri");
3050         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
3051         checkGLcall("glTexParameteri");
3052
3053         glReadBuffer(GL_BACK);
3054         checkGLcall("glReadBuffer(GL_BACK)");
3055
3056         if(texture_target != GL_TEXTURE_2D) {
3057             glDisable(texture_target);
3058             glEnable(GL_TEXTURE_2D);
3059             texture_target = GL_TEXTURE_2D;
3060         }
3061     }
3062     checkGLcall("glEnd and previous");
3063
3064     left = src_rect->left;
3065     right = src_rect->right;
3066
3067     if (upsidedown)
3068     {
3069         top = src_surface->currentDesc.Height - src_rect->top;
3070         bottom = src_surface->currentDesc.Height - src_rect->bottom;
3071     }
3072     else
3073     {
3074         top = src_surface->currentDesc.Height - src_rect->bottom;
3075         bottom = src_surface->currentDesc.Height - src_rect->top;
3076     }
3077
3078     if (src_surface->Flags & SFLAG_NORMCOORD)
3079     {
3080         left /= src_surface->pow2Width;
3081         right /= src_surface->pow2Width;
3082         top /= src_surface->pow2Height;
3083         bottom /= src_surface->pow2Height;
3084     }
3085
3086     /* draw the source texture stretched and upside down. The correct surface is bound already */
3087     glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
3088     glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
3089
3090     context_set_draw_buffer(context, drawBuffer);
3091     glReadBuffer(drawBuffer);
3092
3093     glBegin(GL_QUADS);
3094         /* bottom left */
3095         glTexCoord2f(left, bottom);
3096         glVertex2i(0, fbheight);
3097
3098         /* top left */
3099         glTexCoord2f(left, top);
3100         glVertex2i(0, fbheight - dst_rect.bottom - dst_rect.top);
3101
3102         /* top right */
3103         glTexCoord2f(right, top);
3104         glVertex2i(dst_rect.right - dst_rect.left, fbheight - dst_rect.bottom - dst_rect.top);
3105
3106         /* bottom right */
3107         glTexCoord2f(right, bottom);
3108         glVertex2i(dst_rect.right - dst_rect.left, fbheight);
3109     glEnd();
3110     checkGLcall("glEnd and previous");
3111
3112     if (texture_target != dst_surface->texture_target)
3113     {
3114         glDisable(texture_target);
3115         glEnable(dst_surface->texture_target);
3116         texture_target = dst_surface->texture_target;
3117     }
3118
3119     /* Now read the stretched and upside down image into the destination texture */
3120     glBindTexture(texture_target, dst_surface->texture_name);
3121     checkGLcall("glBindTexture");
3122     glCopyTexSubImage2D(texture_target,
3123                         0,
3124                         dst_rect.left, dst_rect.top, /* xoffset, yoffset */
3125                         0, 0, /* We blitted the image to the origin */
3126                         dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top);
3127     checkGLcall("glCopyTexSubImage2D");
3128
3129     if(drawBuffer == GL_BACK) {
3130         /* Write the back buffer backup back */
3131         if(backup) {
3132             if(texture_target != GL_TEXTURE_2D) {
3133                 glDisable(texture_target);
3134                 glEnable(GL_TEXTURE_2D);
3135                 texture_target = GL_TEXTURE_2D;
3136             }
3137             glBindTexture(GL_TEXTURE_2D, backup);
3138             checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
3139         }
3140         else
3141         {
3142             if (texture_target != src_surface->texture_target)
3143             {
3144                 glDisable(texture_target);
3145                 glEnable(src_surface->texture_target);
3146                 texture_target = src_surface->texture_target;
3147             }
3148             glBindTexture(src_surface->texture_target, src_surface->texture_name);
3149             checkGLcall("glBindTexture(src_surface->texture_target, src_surface->texture_name)");
3150         }
3151
3152         glBegin(GL_QUADS);
3153             /* top left */
3154             glTexCoord2f(0.0f, (float)fbheight / (float)src_surface->pow2Height);
3155             glVertex2i(0, 0);
3156
3157             /* bottom left */
3158             glTexCoord2f(0.0f, 0.0f);
3159             glVertex2i(0, fbheight);
3160
3161             /* bottom right */
3162             glTexCoord2f((float)fbwidth / (float)src_surface->pow2Width, 0.0f);
3163             glVertex2i(fbwidth, src_surface->currentDesc.Height);
3164
3165             /* top right */
3166             glTexCoord2f((float)fbwidth / (float)src_surface->pow2Width,
3167                     (float)fbheight / (float)src_surface->pow2Height);
3168             glVertex2i(fbwidth, 0);
3169         glEnd();
3170     }
3171     glDisable(texture_target);
3172     checkGLcall("glDisable(texture_target)");
3173
3174     /* Cleanup */
3175     if (src != src_surface->texture_name && src != backup)
3176     {
3177         glDeleteTextures(1, &src);
3178         checkGLcall("glDeleteTextures(1, &src)");
3179     }
3180     if(backup) {
3181         glDeleteTextures(1, &backup);
3182         checkGLcall("glDeleteTextures(1, &backup)");
3183     }
3184
3185     LEAVE_GL();
3186
3187     if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
3188
3189     context_release(context);
3190
3191     /* The texture is now most up to date - If the surface is a render target and has a drawable, this
3192      * path is never entered
3193      */
3194     surface_modify_location(dst_surface, SFLAG_INTEXTURE, TRUE);
3195 }
3196
3197 /* Until the blit_shader is ready, define some prototypes here. */
3198 static BOOL fbo_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
3199         const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool, const struct wined3d_format *src_format,
3200         const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool, const struct wined3d_format *dst_format);
3201
3202 /* Front buffer coordinates are always full screen coordinates, but our GL
3203  * drawable is limited to the window's client area. The sysmem and texture
3204  * copies do have the full screen size. Note that GL has a bottom-left
3205  * origin, while D3D has a top-left origin. */
3206 void surface_translate_frontbuffer_coords(IWineD3DSurfaceImpl *surface, HWND window, RECT *rect)
3207 {
3208     POINT offset = {0, surface->currentDesc.Height};
3209     RECT windowsize;
3210
3211     GetClientRect(window, &windowsize);
3212     offset.y -= windowsize.bottom - windowsize.top;
3213     ScreenToClient(window, &offset);
3214     OffsetRect(rect, offset.x, offset.y);
3215 }
3216
3217 static BOOL surface_is_full_rect(IWineD3DSurfaceImpl *surface, const RECT *r)
3218 {
3219     if ((r->left && r->right) || abs(r->right - r->left) != surface->currentDesc.Width)
3220         return FALSE;
3221     if ((r->top && r->bottom) || abs(r->bottom - r->top) != surface->currentDesc.Height)
3222         return FALSE;
3223     return TRUE;
3224 }
3225
3226 /* blit between surface locations. onscreen on different swapchains is not supported.
3227  * depth / stencil is not supported. */
3228 static void surface_blt_fbo(IWineD3DDeviceImpl *device, const WINED3DTEXTUREFILTERTYPE filter,
3229         IWineD3DSurfaceImpl *src_surface, DWORD src_location, const RECT *src_rect_in,
3230         IWineD3DSurfaceImpl *dst_surface, DWORD dst_location, const RECT *dst_rect_in)
3231 {
3232     const struct wined3d_gl_info *gl_info;
3233     struct wined3d_context *context;
3234     RECT src_rect, dst_rect;
3235     GLenum gl_filter;
3236
3237     TRACE("device %p, filter %s,\n", device, debug_d3dtexturefiltertype(filter));
3238     TRACE("src_surface %p, src_location %s, src_rect %s,\n",
3239             src_surface, debug_surflocation(src_location), wine_dbgstr_rect(src_rect_in));
3240     TRACE("dst_surface %p, dst_location %s, dst_rect %s.\n",
3241             dst_surface, debug_surflocation(dst_location), wine_dbgstr_rect(dst_rect_in));
3242
3243     src_rect = *src_rect_in;
3244     dst_rect = *dst_rect_in;
3245
3246     switch (filter)
3247     {
3248         case WINED3DTEXF_LINEAR:
3249             gl_filter = GL_LINEAR;
3250             break;
3251
3252         default:
3253             FIXME("Unsupported filter mode %s (%#x).\n", debug_d3dtexturefiltertype(filter), filter);
3254         case WINED3DTEXF_NONE:
3255         case WINED3DTEXF_POINT:
3256             gl_filter = GL_NEAREST;
3257             break;
3258     }
3259
3260     if (src_location == SFLAG_INDRAWABLE && surface_is_offscreen(src_surface))
3261         src_location = SFLAG_INTEXTURE;
3262     if (dst_location == SFLAG_INDRAWABLE && surface_is_offscreen(dst_surface))
3263         dst_location = SFLAG_INTEXTURE;
3264
3265     /* Make sure the locations are up-to-date. Loading the destination
3266      * surface isn't required if the entire surface is overwritten. (And is
3267      * in fact harmful if we're being called by surface_load_location() with
3268      * the purpose of loading the destination surface.) */
3269     surface_load_location(src_surface, src_location, NULL);
3270     if (!surface_is_full_rect(dst_surface, &dst_rect))
3271         surface_load_location(dst_surface, dst_location, NULL);
3272
3273     if (src_location == SFLAG_INDRAWABLE) context = context_acquire(device, src_surface);
3274     else if (dst_location == SFLAG_INDRAWABLE) context = context_acquire(device, dst_surface);
3275     else context = context_acquire(device, NULL);
3276
3277     if (!context->valid)
3278     {
3279         context_release(context);
3280         WARN("Invalid context, skipping blit.\n");
3281         return;
3282     }
3283
3284     gl_info = context->gl_info;
3285
3286     if (src_location == SFLAG_INDRAWABLE)
3287     {
3288         GLenum buffer = surface_get_gl_buffer(src_surface);
3289
3290         TRACE("Source surface %p is onscreen.\n", src_surface);
3291
3292         if (buffer == GL_FRONT)
3293             surface_translate_frontbuffer_coords(src_surface, context->win_handle, &src_rect);
3294
3295         src_rect.top = src_surface->currentDesc.Height - src_rect.top;
3296         src_rect.bottom = src_surface->currentDesc.Height - src_rect.bottom;
3297
3298         ENTER_GL();
3299         context_bind_fbo(context, GL_READ_FRAMEBUFFER, NULL);
3300         glReadBuffer(buffer);
3301         checkGLcall("glReadBuffer()");
3302     }
3303     else
3304     {
3305         TRACE("Source surface %p is offscreen.\n", src_surface);
3306         ENTER_GL();
3307         context_apply_fbo_state_blit(context, GL_READ_FRAMEBUFFER, src_surface, NULL, src_location);
3308         glReadBuffer(GL_COLOR_ATTACHMENT0);
3309         checkGLcall("glReadBuffer()");
3310     }
3311     LEAVE_GL();
3312
3313     if (dst_location == SFLAG_INDRAWABLE)
3314     {
3315         GLenum buffer = surface_get_gl_buffer(dst_surface);
3316
3317         TRACE("Destination surface %p is onscreen.\n", dst_surface);
3318
3319         if (buffer == GL_FRONT)
3320             surface_translate_frontbuffer_coords(dst_surface, context->win_handle, &dst_rect);
3321
3322         dst_rect.top = dst_surface->currentDesc.Height - dst_rect.top;
3323         dst_rect.bottom = dst_surface->currentDesc.Height - dst_rect.bottom;
3324
3325         ENTER_GL();
3326         context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, NULL);
3327         context_set_draw_buffer(context, buffer);
3328     }
3329     else
3330     {
3331         TRACE("Destination surface %p is offscreen.\n", dst_surface);
3332
3333         ENTER_GL();
3334         context_apply_fbo_state_blit(context, GL_DRAW_FRAMEBUFFER, dst_surface, NULL, dst_location);
3335         context_set_draw_buffer(context, GL_COLOR_ATTACHMENT0);
3336     }
3337
3338     glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
3339     IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
3340     IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
3341     IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
3342     IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
3343
3344     glDisable(GL_SCISSOR_TEST);
3345     IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
3346
3347     gl_info->fbo_ops.glBlitFramebuffer(src_rect.left, src_rect.top, src_rect.right, src_rect.bottom,
3348             dst_rect.left, dst_rect.top, dst_rect.right, dst_rect.bottom, GL_COLOR_BUFFER_BIT, gl_filter);
3349     checkGLcall("glBlitFramebuffer()");
3350
3351     LEAVE_GL();
3352
3353     if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
3354
3355     context_release(context);
3356 }
3357
3358 /* Do not call while under the GL lock. */
3359 HRESULT surface_color_fill(IWineD3DSurfaceImpl *s, const RECT *rect, const WINED3DCOLORVALUE *color)
3360 {
3361     IWineD3DDeviceImpl *device = s->resource.device;
3362     const struct blit_shader *blitter;
3363
3364     blitter = wined3d_select_blitter(&device->adapter->gl_info, BLIT_OP_COLOR_FILL,
3365             NULL, 0, 0, NULL, rect, s->resource.usage, s->resource.pool, s->resource.format);
3366     if (!blitter)
3367     {
3368         FIXME("No blitter is capable of performing the requested color fill operation.\n");
3369         return WINED3DERR_INVALIDCALL;
3370     }
3371
3372     return blitter->color_fill(device, s, rect, color);
3373 }
3374
3375 /* Not called from the VTable */
3376 /* Do not call while under the GL lock. */
3377 static HRESULT IWineD3DSurfaceImpl_BltOverride(IWineD3DSurfaceImpl *dst_surface, const RECT *DestRect,
3378         IWineD3DSurfaceImpl *src_surface, const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx,
3379         WINED3DTEXTUREFILTERTYPE Filter)
3380 {
3381     IWineD3DDeviceImpl *device = dst_surface->resource.device;
3382     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3383     IWineD3DSwapChainImpl *srcSwapchain = NULL, *dstSwapchain = NULL;
3384     RECT dst_rect, src_rect;
3385
3386     TRACE("dst_surface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, blt_fx %p, filter %s.\n",
3387             dst_surface, wine_dbgstr_rect(DestRect), src_surface, wine_dbgstr_rect(SrcRect),
3388             Flags, DDBltFx, debug_d3dtexturefiltertype(Filter));
3389
3390     /* Get the swapchain. One of the surfaces has to be a primary surface */
3391     if (dst_surface->resource.pool == WINED3DPOOL_SYSTEMMEM)
3392     {
3393         WARN("Destination is in sysmem, rejecting gl blt\n");
3394         return WINED3DERR_INVALIDCALL;
3395     }
3396
3397     if (dst_surface->container.type == WINED3D_CONTAINER_SWAPCHAIN)
3398         dstSwapchain = dst_surface->container.u.swapchain;
3399
3400     if (src_surface)
3401     {
3402         if (src_surface->resource.pool == WINED3DPOOL_SYSTEMMEM)
3403         {
3404             WARN("Src is in sysmem, rejecting gl blt\n");
3405             return WINED3DERR_INVALIDCALL;
3406         }
3407
3408         if (src_surface->container.type == WINED3D_CONTAINER_SWAPCHAIN)
3409             srcSwapchain = src_surface->container.u.swapchain;
3410     }
3411
3412     /* Early sort out of cases where no render target is used */
3413     if (!dstSwapchain && !srcSwapchain
3414             && src_surface != device->render_targets[0]
3415             && dst_surface != device->render_targets[0])
3416     {
3417         TRACE("No surface is render target, not using hardware blit.\n");
3418         return WINED3DERR_INVALIDCALL;
3419     }
3420
3421     /* No destination color keying supported */
3422     if(Flags & (WINEDDBLT_KEYDEST | WINEDDBLT_KEYDESTOVERRIDE)) {
3423         /* Can we support that with glBlendFunc if blitting to the frame buffer? */
3424         TRACE("Destination color key not supported in accelerated Blit, falling back to software\n");
3425         return WINED3DERR_INVALIDCALL;
3426     }
3427
3428     surface_get_rect(dst_surface, DestRect, &dst_rect);
3429     if (src_surface) surface_get_rect(src_surface, SrcRect, &src_rect);
3430
3431     /* The only case where both surfaces on a swapchain are supported is a back buffer -> front buffer blit on the same swapchain */
3432     if (dstSwapchain && dstSwapchain == srcSwapchain && dstSwapchain->back_buffers
3433             && dst_surface == dstSwapchain->front_buffer
3434             && src_surface == dstSwapchain->back_buffers[0])
3435     {
3436         /* Half-Life does a Blt from the back buffer to the front buffer,
3437          * Full surface size, no flags... Use present instead
3438          *
3439          * This path will only be entered for d3d7 and ddraw apps, because d3d8/9 offer no way to blit TO the front buffer
3440          */
3441
3442         /* Check rects - IWineD3DDevice_Present doesn't handle them */
3443         while(1)
3444         {
3445             TRACE("Looking if a Present can be done...\n");
3446             /* Source Rectangle must be full surface */
3447             if (src_rect.left || src_rect.top
3448                     || src_rect.right != src_surface->currentDesc.Width
3449                     || src_rect.bottom != src_surface->currentDesc.Height)
3450             {
3451                 TRACE("No, Source rectangle doesn't match\n");
3452                 break;
3453             }
3454
3455             /* No stretching may occur */
3456             if(src_rect.right != dst_rect.right - dst_rect.left ||
3457                src_rect.bottom != dst_rect.bottom - dst_rect.top) {
3458                 TRACE("No, stretching is done\n");
3459                 break;
3460             }
3461
3462             /* Destination must be full surface or match the clipping rectangle */
3463             if (dst_surface->clipper && ((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd)
3464             {
3465                 RECT cliprect;
3466                 POINT pos[2];
3467                 GetClientRect(((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd, &cliprect);
3468                 pos[0].x = dst_rect.left;
3469                 pos[0].y = dst_rect.top;
3470                 pos[1].x = dst_rect.right;
3471                 pos[1].y = dst_rect.bottom;
3472                 MapWindowPoints(GetDesktopWindow(), ((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd, pos, 2);
3473
3474                 if(pos[0].x != cliprect.left  || pos[0].y != cliprect.top   ||
3475                    pos[1].x != cliprect.right || pos[1].y != cliprect.bottom)
3476                 {
3477                     TRACE("No, dest rectangle doesn't match(clipper)\n");
3478                     TRACE("Clip rect at %s\n", wine_dbgstr_rect(&cliprect));
3479                     TRACE("Blt dest: %s\n", wine_dbgstr_rect(&dst_rect));
3480                     break;
3481                 }
3482             }
3483             else if (dst_rect.left || dst_rect.top
3484                     || dst_rect.right != dst_surface->currentDesc.Width
3485                     || dst_rect.bottom != dst_surface->currentDesc.Height)
3486             {
3487                 TRACE("No, dest rectangle doesn't match(surface size)\n");
3488                 break;
3489             }
3490
3491             TRACE("Yes\n");
3492
3493             /* These flags are unimportant for the flag check, remove them */
3494             if (!(Flags & ~(WINEDDBLT_DONOTWAIT | WINEDDBLT_WAIT)))
3495             {
3496                 WINED3DSWAPEFFECT orig_swap = dstSwapchain->presentParms.SwapEffect;
3497
3498                 /* The idea behind this is that a glReadPixels and a glDrawPixels call
3499                     * take very long, while a flip is fast.
3500                     * This applies to Half-Life, which does such Blts every time it finished
3501                     * a frame, and to Prince of Persia 3D, which uses this to draw at least the main
3502                     * menu. This is also used by all apps when they do windowed rendering
3503                     *
3504                     * The problem is that flipping is not really the same as copying. After a
3505                     * Blt the front buffer is a copy of the back buffer, and the back buffer is
3506                     * untouched. Therefore it's necessary to override the swap effect
3507                     * and to set it back after the flip.
3508                     *
3509                     * Windowed Direct3D < 7 apps do the same. The D3D7 sdk demos are nice
3510                     * testcases.
3511                     */
3512
3513                 dstSwapchain->presentParms.SwapEffect = WINED3DSWAPEFFECT_COPY;
3514                 dstSwapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
3515
3516                 TRACE("Full screen back buffer -> front buffer blt, performing a flip instead\n");
3517                 IWineD3DSwapChain_Present((IWineD3DSwapChain *)dstSwapchain,
3518                         NULL, NULL, dstSwapchain->win_handle, NULL, 0);
3519
3520                 dstSwapchain->presentParms.SwapEffect = orig_swap;
3521
3522                 return WINED3D_OK;
3523             }
3524             break;
3525         }
3526
3527         TRACE("Unsupported blit between buffers on the same swapchain\n");
3528         return WINED3DERR_INVALIDCALL;
3529     } else if(dstSwapchain && dstSwapchain == srcSwapchain) {
3530         FIXME("Implement hardware blit between two surfaces on the same swapchain\n");
3531         return WINED3DERR_INVALIDCALL;
3532     } else if(dstSwapchain && srcSwapchain) {
3533         FIXME("Implement hardware blit between two different swapchains\n");
3534         return WINED3DERR_INVALIDCALL;
3535     }
3536     else if (dstSwapchain)
3537     {
3538         /* Handled with regular texture -> swapchain blit */
3539         if (src_surface == device->render_targets[0])
3540             TRACE("Blit from active render target to a swapchain\n");
3541     }
3542     else if (srcSwapchain && dst_surface == device->render_targets[0])
3543     {
3544         FIXME("Implement blit from a swapchain to the active render target\n");
3545         return WINED3DERR_INVALIDCALL;
3546     }
3547
3548     if ((srcSwapchain || src_surface == device->render_targets[0]) && !dstSwapchain)
3549     {
3550         /* Blit from render target to texture */
3551         BOOL stretchx;
3552
3553         /* P8 read back is not implemented */
3554         if (src_surface->resource.format->id == WINED3DFMT_P8_UINT
3555                 || dst_surface->resource.format->id == WINED3DFMT_P8_UINT)
3556         {
3557             TRACE("P8 read back not supported by frame buffer to texture blit\n");
3558             return WINED3DERR_INVALIDCALL;
3559         }
3560
3561         if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3562             TRACE("Color keying not supported by frame buffer to texture blit\n");
3563             return WINED3DERR_INVALIDCALL;
3564             /* Destination color key is checked above */
3565         }
3566
3567         if(dst_rect.right - dst_rect.left != src_rect.right - src_rect.left) {
3568             stretchx = TRUE;
3569         } else {
3570             stretchx = FALSE;
3571         }
3572
3573         /* Blt is a pretty powerful call, while glCopyTexSubImage2D is not. glCopyTexSubImage cannot
3574          * flip the image nor scale it.
3575          *
3576          * -> If the app asks for a unscaled, upside down copy, just perform one glCopyTexSubImage2D call
3577          * -> If the app wants a image width an unscaled width, copy it line per line
3578          * -> If the app wants a image that is scaled on the x axis, and the destination rectangle is smaller
3579          *    than the frame buffer, draw an upside down scaled image onto the fb, read it back and restore the
3580          *    back buffer. This is slower than reading line per line, thus not used for flipping
3581          * -> If the app wants a scaled image with a dest rect that is bigger than the fb, it has to be copied
3582          *    pixel by pixel
3583          *
3584          * If EXT_framebuffer_blit is supported that can be used instead. Note that EXT_framebuffer_blit implies
3585          * FBO support, so it doesn't really make sense to try and make it work with different offscreen rendering
3586          * backends.
3587          */
3588         if (fbo_blit_supported(gl_info, BLIT_OP_BLIT,
3589                 &src_rect, src_surface->resource.usage, src_surface->resource.pool, src_surface->resource.format,
3590                 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool, dst_surface->resource.format))
3591         {
3592             surface_blt_fbo(device, Filter,
3593                     src_surface, SFLAG_INDRAWABLE, &src_rect,
3594                     dst_surface, SFLAG_INDRAWABLE, &dst_rect);
3595             surface_modify_location(dst_surface, SFLAG_INDRAWABLE, TRUE);
3596         }
3597         else if (!stretchx || dst_rect.right - dst_rect.left > src_surface->currentDesc.Width
3598                 || dst_rect.bottom - dst_rect.top > src_surface->currentDesc.Height)
3599         {
3600             TRACE("No stretching in x direction, using direct framebuffer -> texture copy\n");
3601             fb_copy_to_texture_direct(dst_surface, src_surface, &src_rect, &dst_rect, Filter);
3602         } else {
3603             TRACE("Using hardware stretching to flip / stretch the texture\n");
3604             fb_copy_to_texture_hwstretch(dst_surface, src_surface, &src_rect, &dst_rect, Filter);
3605         }
3606
3607         if (!(dst_surface->Flags & SFLAG_DONOTFREE))
3608         {
3609             HeapFree(GetProcessHeap(), 0, dst_surface->resource.heapMemory);
3610             dst_surface->resource.allocatedMemory = NULL;
3611             dst_surface->resource.heapMemory = NULL;
3612         }
3613         else
3614         {
3615             dst_surface->Flags &= ~SFLAG_INSYSMEM;
3616         }
3617
3618         return WINED3D_OK;
3619     }
3620     else if (src_surface)
3621     {
3622         /* Blit from offscreen surface to render target */
3623         DWORD oldCKeyFlags = src_surface->CKeyFlags;
3624         WINEDDCOLORKEY oldBltCKey = src_surface->SrcBltCKey;
3625         struct wined3d_context *context;
3626
3627         TRACE("Blt from surface %p to rendertarget %p\n", src_surface, dst_surface);
3628
3629         if (!(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE))
3630                 && fbo_blit_supported(gl_info, BLIT_OP_BLIT,
3631                         &src_rect, src_surface->resource.usage, src_surface->resource.pool,
3632                         src_surface->resource.format,
3633                         &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3634                         dst_surface->resource.format))
3635         {
3636             TRACE("Using surface_blt_fbo.\n");
3637             /* The source is always a texture, but never the currently active render target, and the texture
3638              * contents are never upside down. */
3639             surface_blt_fbo(device, Filter,
3640                     src_surface, SFLAG_INDRAWABLE, &src_rect,
3641                     dst_surface, SFLAG_INDRAWABLE, &dst_rect);
3642             surface_modify_location(dst_surface, SFLAG_INDRAWABLE, TRUE);
3643             return WINED3D_OK;
3644         }
3645
3646         if (!(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE))
3647                 && arbfp_blit.blit_supported(gl_info, BLIT_OP_BLIT,
3648                         &src_rect, src_surface->resource.usage, src_surface->resource.pool,
3649                         src_surface->resource.format,
3650                         &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3651                         dst_surface->resource.format))
3652         {
3653             return arbfp_blit_surface(device, src_surface, &src_rect, dst_surface, &dst_rect, BLIT_OP_BLIT, Filter);
3654         }
3655
3656         /* Color keying: Check if we have to do a color keyed blt,
3657          * and if not check if a color key is activated.
3658          *
3659          * Just modify the color keying parameters in the surface and restore them afterwards
3660          * The surface keeps track of the color key last used to load the opengl surface.
3661          * PreLoad will catch the change to the flags and color key and reload if necessary.
3662          */
3663         if(Flags & WINEDDBLT_KEYSRC) {
3664             /* Use color key from surface */
3665         } else if(Flags & WINEDDBLT_KEYSRCOVERRIDE) {
3666             /* Use color key from DDBltFx */
3667             src_surface->CKeyFlags |= WINEDDSD_CKSRCBLT;
3668             src_surface->SrcBltCKey = DDBltFx->ddckSrcColorkey;
3669         } else {
3670             /* Do not use color key */
3671             src_surface->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
3672         }
3673
3674         /* Now load the surface */
3675         surface_internal_preload(src_surface, SRGB_RGB);
3676
3677         /* Activate the destination context, set it up for blitting */
3678         context = context_acquire(device, dst_surface);
3679         context_apply_blit_state(context, device);
3680
3681         if (dstSwapchain && dst_surface == dstSwapchain->front_buffer)
3682             surface_translate_frontbuffer_coords(dst_surface, context->win_handle, &dst_rect);
3683         else if (surface_is_offscreen(dst_surface))
3684         {
3685             dst_rect.top = dst_surface->currentDesc.Height - dst_rect.top;
3686             dst_rect.bottom = dst_surface->currentDesc.Height - dst_rect.bottom;
3687         }
3688
3689         if (!device->blitter->blit_supported(gl_info, BLIT_OP_BLIT,
3690                 &src_rect, src_surface->resource.usage, src_surface->resource.pool, src_surface->resource.format,
3691                 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool, dst_surface->resource.format))
3692         {
3693             FIXME("Unsupported blit operation falling back to software\n");
3694             return WINED3DERR_INVALIDCALL;
3695         }
3696
3697         device->blitter->set_shader((IWineD3DDevice *)device, src_surface);
3698
3699         ENTER_GL();
3700
3701         /* This is for color keying */
3702         if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3703             glEnable(GL_ALPHA_TEST);
3704             checkGLcall("glEnable(GL_ALPHA_TEST)");
3705
3706             /* When the primary render target uses P8, the alpha component contains the palette index.
3707              * Which means that the colorkey is one of the palette entries. In other cases pixels that
3708              * should be masked away have alpha set to 0. */
3709             if (primary_render_target_is_p8(device))
3710                 glAlphaFunc(GL_NOTEQUAL, (float)src_surface->SrcBltCKey.dwColorSpaceLowValue / 256.0f);
3711             else
3712                 glAlphaFunc(GL_NOTEQUAL, 0.0f);
3713             checkGLcall("glAlphaFunc");
3714         } else {
3715             glDisable(GL_ALPHA_TEST);
3716             checkGLcall("glDisable(GL_ALPHA_TEST)");
3717         }
3718
3719         /* Draw a textured quad
3720          */
3721         draw_textured_quad(src_surface, &src_rect, &dst_rect, Filter);
3722
3723         if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3724             glDisable(GL_ALPHA_TEST);
3725             checkGLcall("glDisable(GL_ALPHA_TEST)");
3726         }
3727
3728         /* Restore the color key parameters */
3729         src_surface->CKeyFlags = oldCKeyFlags;
3730         src_surface->SrcBltCKey = oldBltCKey;
3731
3732         LEAVE_GL();
3733
3734         /* Leave the opengl state valid for blitting */
3735         device->blitter->unset_shader((IWineD3DDevice *)device);
3736
3737         if (wined3d_settings.strict_draw_ordering || (dstSwapchain
3738                 && (dst_surface == dstSwapchain->front_buffer
3739                 || dstSwapchain->num_contexts > 1)))
3740             wglFlush(); /* Flush to ensure ordering across contexts. */
3741
3742         context_release(context);
3743
3744         /* TODO: If the surface is locked often, perform the Blt in software on the memory instead */
3745         /* The surface is now in the drawable. On onscreen surfaces or without fbos the texture
3746          * is outdated now
3747          */
3748         surface_modify_location(dst_surface, SFLAG_INDRAWABLE, TRUE);
3749
3750         return WINED3D_OK;
3751     }
3752     else
3753     {
3754         /* Source-Less Blit to render target */
3755         if (Flags & WINEDDBLT_COLORFILL)
3756         {
3757             WINED3DCOLORVALUE color;
3758
3759             TRACE("Colorfill\n");
3760
3761             /* The color as given in the Blt function is in the surface format. */
3762             if (!surface_convert_color_to_float(dst_surface, DDBltFx->u5.dwFillColor, &color))
3763                 return WINED3DERR_INVALIDCALL;
3764
3765             return surface_color_fill(dst_surface, &dst_rect, &color);
3766         }
3767     }
3768
3769     /* Default: Fall back to the generic blt. Not an error, a TRACE is enough */
3770     TRACE("Didn't find any usable render target setup for hw blit, falling back to software\n");
3771     return WINED3DERR_INVALIDCALL;
3772 }
3773
3774 static HRESULT IWineD3DSurfaceImpl_BltZ(IWineD3DSurfaceImpl *This, const RECT *DestRect,
3775         IWineD3DSurface *src_surface, const RECT *src_rect, DWORD Flags, const WINEDDBLTFX *DDBltFx)
3776 {
3777     IWineD3DDeviceImpl *device = This->resource.device;
3778     float depth;
3779
3780     if (Flags & WINEDDBLT_DEPTHFILL)
3781     {
3782         switch (This->resource.format->id)
3783         {
3784             case WINED3DFMT_D16_UNORM:
3785                 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000ffff;
3786                 break;
3787             case WINED3DFMT_S1_UINT_D15_UNORM:
3788                 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00007fff;
3789                 break;
3790             case WINED3DFMT_D24_UNORM_S8_UINT:
3791             case WINED3DFMT_X8D24_UNORM:
3792                 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00ffffff;
3793                 break;
3794             case WINED3DFMT_D32_UNORM:
3795                 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0xffffffff;
3796                 break;
3797             default:
3798                 depth = 0.0f;
3799                 ERR("Unexpected format for depth fill: %s.\n", debug_d3dformat(This->resource.format->id));
3800         }
3801
3802         return IWineD3DDevice_Clear((IWineD3DDevice *)device, DestRect ? 1 : 0, DestRect,
3803                 WINED3DCLEAR_ZBUFFER, 0x00000000, depth, 0x00000000);
3804     }
3805
3806     FIXME("(%p): Unsupp depthstencil blit\n", This);
3807     return WINED3DERR_INVALIDCALL;
3808 }
3809
3810 static HRESULT WINAPI IWineD3DSurfaceImpl_Blt(IWineD3DSurface *iface, const RECT *DestRect,
3811         IWineD3DSurface *src_surface, const RECT *SrcRect, DWORD Flags,
3812         const WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter)
3813 {
3814     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3815     IWineD3DSurfaceImpl *src = (IWineD3DSurfaceImpl *)src_surface;
3816     IWineD3DDeviceImpl *device = This->resource.device;
3817
3818     TRACE("iface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, fx %p, filter %s.\n",
3819             iface, wine_dbgstr_rect(DestRect), src_surface, wine_dbgstr_rect(SrcRect),
3820             Flags, DDBltFx, debug_d3dtexturefiltertype(Filter));
3821     TRACE("Usage is %s.\n", debug_d3dusage(This->resource.usage));
3822
3823     if ((This->Flags & SFLAG_LOCKED) || (src && (src->Flags & SFLAG_LOCKED)))
3824     {
3825         WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3826         return WINEDDERR_SURFACEBUSY;
3827     }
3828
3829     /* Accessing the depth stencil is supposed to fail between a BeginScene and EndScene pair,
3830      * except depth blits, which seem to work
3831      */
3832     if (This == device->depth_stencil || (src && src == device->depth_stencil))
3833     {
3834         if (device->inScene && !(Flags & WINEDDBLT_DEPTHFILL))
3835         {
3836             TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3837             return WINED3DERR_INVALIDCALL;
3838         }
3839         else if (SUCCEEDED(IWineD3DSurfaceImpl_BltZ(This, DestRect, src_surface, SrcRect, Flags, DDBltFx)))
3840         {
3841             TRACE("Z Blit override handled the blit\n");
3842             return WINED3D_OK;
3843         }
3844     }
3845
3846     /* Special cases for RenderTargets */
3847     if ((This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3848             || (src && (src->resource.usage & WINED3DUSAGE_RENDERTARGET)))
3849     {
3850         if (SUCCEEDED(IWineD3DSurfaceImpl_BltOverride(This, DestRect, src, SrcRect, Flags, DDBltFx, Filter)))
3851             return WINED3D_OK;
3852     }
3853
3854     /* For the rest call the X11 surface implementation.
3855      * For RenderTargets this should be implemented OpenGL accelerated in BltOverride,
3856      * other Blts are rather rare. */
3857     return IWineD3DBaseSurfaceImpl_Blt(iface, DestRect, src_surface, SrcRect, Flags, DDBltFx, Filter);
3858 }
3859
3860 static HRESULT WINAPI IWineD3DSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty,
3861         IWineD3DSurface *src_surface, const RECT *rsrc, DWORD trans)
3862 {
3863     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3864     IWineD3DSurfaceImpl *src = (IWineD3DSurfaceImpl *)src_surface;
3865     IWineD3DDeviceImpl *device = This->resource.device;
3866
3867     TRACE("iface %p, dst_x %u, dst_y %u, src_surface %p, src_rect %s, flags %#x.\n",
3868             iface, dstx, dsty, src_surface, wine_dbgstr_rect(rsrc), trans);
3869
3870     if ((This->Flags & SFLAG_LOCKED) || (src->Flags & SFLAG_LOCKED))
3871     {
3872         WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3873         return WINEDDERR_SURFACEBUSY;
3874     }
3875
3876     if (device->inScene && (This == device->depth_stencil || src == device->depth_stencil))
3877     {
3878         TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3879         return WINED3DERR_INVALIDCALL;
3880     }
3881
3882     /* Special cases for RenderTargets */
3883     if ((This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3884             || (src->resource.usage & WINED3DUSAGE_RENDERTARGET))
3885     {
3886
3887         RECT SrcRect, DstRect;
3888         DWORD Flags=0;
3889
3890         surface_get_rect(src, rsrc, &SrcRect);
3891
3892         DstRect.left = dstx;
3893         DstRect.top=dsty;
3894         DstRect.right = dstx + SrcRect.right - SrcRect.left;
3895         DstRect.bottom = dsty + SrcRect.bottom - SrcRect.top;
3896
3897         /* Convert BltFast flags into Btl ones because it is called from SurfaceImpl_Blt as well */
3898         if(trans & WINEDDBLTFAST_SRCCOLORKEY)
3899             Flags |= WINEDDBLT_KEYSRC;
3900         if(trans & WINEDDBLTFAST_DESTCOLORKEY)
3901             Flags |= WINEDDBLT_KEYDEST;
3902         if(trans & WINEDDBLTFAST_WAIT)
3903             Flags |= WINEDDBLT_WAIT;
3904         if(trans & WINEDDBLTFAST_DONOTWAIT)
3905             Flags |= WINEDDBLT_DONOTWAIT;
3906
3907         if (SUCCEEDED(IWineD3DSurfaceImpl_BltOverride(This,
3908                 &DstRect, src, &SrcRect, Flags, NULL, WINED3DTEXF_POINT)))
3909             return WINED3D_OK;
3910     }
3911
3912     return IWineD3DBaseSurfaceImpl_BltFast(iface, dstx, dsty, src_surface, rsrc, trans);
3913 }
3914
3915 static HRESULT WINAPI IWineD3DSurfaceImpl_RealizePalette(IWineD3DSurface *iface)
3916 {
3917     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3918     RGBQUAD col[256];
3919     IWineD3DPaletteImpl *pal = This->palette;
3920     unsigned int n;
3921     TRACE("(%p)\n", This);
3922
3923     if (!pal) return WINED3D_OK;
3924
3925     if (This->resource.format->id == WINED3DFMT_P8_UINT
3926             || This->resource.format->id == WINED3DFMT_P8_UINT_A8_UNORM)
3927     {
3928         if (This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3929         {
3930             /* Make sure the texture is up to date. This call doesn't do
3931              * anything if the texture is already up to date. */
3932             surface_load_location(This, SFLAG_INTEXTURE, NULL);
3933
3934             /* We want to force a palette refresh, so mark the drawable as not being up to date */
3935             surface_modify_location(This, SFLAG_INDRAWABLE, FALSE);
3936         }
3937         else
3938         {
3939             if (!(This->Flags & SFLAG_INSYSMEM))
3940             {
3941                 TRACE("Palette changed with surface that does not have an up to date system memory copy.\n");
3942                 surface_load_location(This, SFLAG_INSYSMEM, NULL);
3943             }
3944             TRACE("Dirtifying surface\n");
3945             surface_modify_location(This, SFLAG_INSYSMEM, TRUE);
3946         }
3947     }
3948
3949     if(This->Flags & SFLAG_DIBSECTION) {
3950         TRACE("(%p): Updating the hdc's palette\n", This);
3951         for (n=0; n<256; n++) {
3952             col[n].rgbRed   = pal->palents[n].peRed;
3953             col[n].rgbGreen = pal->palents[n].peGreen;
3954             col[n].rgbBlue  = pal->palents[n].peBlue;
3955             col[n].rgbReserved = 0;
3956         }
3957         SetDIBColorTable(This->hDC, 0, 256, col);
3958     }
3959
3960     /* Propagate the changes to the drawable when we have a palette. */
3961     if (This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3962         surface_load_location(This, SFLAG_INDRAWABLE, NULL);
3963
3964     return WINED3D_OK;
3965 }
3966
3967 static HRESULT WINAPI IWineD3DSurfaceImpl_PrivateSetup(IWineD3DSurface *iface) {
3968     /** Check against the maximum texture sizes supported by the video card **/
3969     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3970     const struct wined3d_gl_info *gl_info = &This->resource.device->adapter->gl_info;
3971     unsigned int pow2Width, pow2Height;
3972
3973     This->texture_name = 0;
3974     This->texture_target = GL_TEXTURE_2D;
3975
3976     /* Non-power2 support */
3977     if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] || gl_info->supported[WINED3D_GL_NORMALIZED_TEXRECT])
3978     {
3979         pow2Width = This->currentDesc.Width;
3980         pow2Height = This->currentDesc.Height;
3981     }
3982     else
3983     {
3984         /* Find the nearest pow2 match */
3985         pow2Width = pow2Height = 1;
3986         while (pow2Width < This->currentDesc.Width) pow2Width <<= 1;
3987         while (pow2Height < This->currentDesc.Height) pow2Height <<= 1;
3988     }
3989     This->pow2Width  = pow2Width;
3990     This->pow2Height = pow2Height;
3991
3992     if (pow2Width > This->currentDesc.Width || pow2Height > This->currentDesc.Height)
3993     {
3994         /* TODO: Add support for non power two compressed textures. */
3995         if (This->resource.format->Flags & WINED3DFMT_FLAG_COMPRESSED)
3996         {
3997             FIXME("(%p) Compressed non-power-two textures are not supported w(%d) h(%d)\n",
3998                   This, This->currentDesc.Width, This->currentDesc.Height);
3999             return WINED3DERR_NOTAVAILABLE;
4000         }
4001     }
4002
4003     if(pow2Width != This->currentDesc.Width ||
4004        pow2Height != This->currentDesc.Height) {
4005         This->Flags |= SFLAG_NONPOW2;
4006     }
4007
4008     TRACE("%p\n", This);
4009     if ((This->pow2Width > gl_info->limits.texture_size || This->pow2Height > gl_info->limits.texture_size)
4010             && !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL)))
4011     {
4012         /* one of three options
4013         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)
4014         2: Set the texture to the maximum size (bad idea)
4015         3:    WARN and return WINED3DERR_NOTAVAILABLE;
4016         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.
4017         */
4018         if(This->resource.pool == WINED3DPOOL_DEFAULT || This->resource.pool == WINED3DPOOL_MANAGED)
4019         {
4020             WARN("(%p) Unable to allocate a surface which exceeds the maximum OpenGL texture size\n", This);
4021             return WINED3DERR_NOTAVAILABLE;
4022         }
4023
4024         /* We should never use this surface in combination with OpenGL! */
4025         TRACE("(%p) Creating an oversized surface: %ux%u\n", This, This->pow2Width, This->pow2Height);
4026     }
4027     else
4028     {
4029         /* Don't use ARB_TEXTURE_RECTANGLE in case the surface format is P8 and EXT_PALETTED_TEXTURE
4030            is used in combination with texture uploads (RTL_READTEX/RTL_TEXTEX). The reason is that EXT_PALETTED_TEXTURE
4031            doesn't work in combination with ARB_TEXTURE_RECTANGLE.
4032         */
4033         if (This->Flags & SFLAG_NONPOW2 && gl_info->supported[ARB_TEXTURE_RECTANGLE]
4034                 && !(This->resource.format->id == WINED3DFMT_P8_UINT
4035                 && gl_info->supported[EXT_PALETTED_TEXTURE]
4036                 && wined3d_settings.rendertargetlock_mode == RTL_READTEX))
4037         {
4038             This->texture_target = GL_TEXTURE_RECTANGLE_ARB;
4039             This->pow2Width  = This->currentDesc.Width;
4040             This->pow2Height = This->currentDesc.Height;
4041             This->Flags &= ~(SFLAG_NONPOW2 | SFLAG_NORMCOORD);
4042         }
4043     }
4044
4045     switch (wined3d_settings.offscreen_rendering_mode)
4046     {
4047         case ORM_FBO:
4048             This->get_drawable_size = get_drawable_size_fbo;
4049             break;
4050
4051         case ORM_BACKBUFFER:
4052             This->get_drawable_size = get_drawable_size_backbuffer;
4053             break;
4054
4055         default:
4056             ERR("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
4057             return WINED3DERR_INVALIDCALL;
4058     }
4059
4060     This->Flags |= SFLAG_INSYSMEM;
4061
4062     return WINED3D_OK;
4063 }
4064
4065 /* GL locking is done by the caller */
4066 static void surface_depth_blt(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
4067         GLuint texture, GLsizei w, GLsizei h, GLenum target)
4068 {
4069     IWineD3DDeviceImpl *device = This->resource.device;
4070     GLint compare_mode = GL_NONE;
4071     struct blt_info info;
4072     GLint old_binding = 0;
4073
4074     glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_VIEWPORT_BIT);
4075
4076     glDisable(GL_CULL_FACE);
4077     glDisable(GL_BLEND);
4078     glDisable(GL_ALPHA_TEST);
4079     glDisable(GL_SCISSOR_TEST);
4080     glDisable(GL_STENCIL_TEST);
4081     glEnable(GL_DEPTH_TEST);
4082     glDepthFunc(GL_ALWAYS);
4083     glDepthMask(GL_TRUE);
4084     glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
4085     glViewport(0, 0, w, h);
4086
4087     surface_get_blt_info(target, NULL, w, h, &info);
4088     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
4089     glGetIntegerv(info.binding, &old_binding);
4090     glBindTexture(info.bind_target, texture);
4091     if (gl_info->supported[ARB_SHADOW])
4092     {
4093         glGetTexParameteriv(info.bind_target, GL_TEXTURE_COMPARE_MODE_ARB, &compare_mode);
4094         if (compare_mode != GL_NONE) glTexParameteri(info.bind_target, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE);
4095     }
4096
4097     device->shader_backend->shader_select_depth_blt((IWineD3DDevice *)device,
4098             info.tex_type, &This->ds_current_size);
4099
4100     glBegin(GL_TRIANGLE_STRIP);
4101     glTexCoord3fv(info.coords[0]);
4102     glVertex2f(-1.0f, -1.0f);
4103     glTexCoord3fv(info.coords[1]);
4104     glVertex2f(1.0f, -1.0f);
4105     glTexCoord3fv(info.coords[2]);
4106     glVertex2f(-1.0f, 1.0f);
4107     glTexCoord3fv(info.coords[3]);
4108     glVertex2f(1.0f, 1.0f);
4109     glEnd();
4110
4111     if (compare_mode != GL_NONE) glTexParameteri(info.bind_target, GL_TEXTURE_COMPARE_MODE_ARB, compare_mode);
4112     glBindTexture(info.bind_target, old_binding);
4113
4114     glPopAttrib();
4115
4116     device->shader_backend->shader_deselect_depth_blt((IWineD3DDevice *)device);
4117 }
4118
4119 void surface_modify_ds_location(IWineD3DSurfaceImpl *surface,
4120         DWORD location, UINT w, UINT h)
4121 {
4122     TRACE("surface %p, new location %#x, w %u, h %u.\n", surface, location, w, h);
4123
4124     if (location & ~SFLAG_DS_LOCATIONS)
4125         FIXME("Invalid location (%#x) specified.\n", location);
4126
4127     surface->ds_current_size.cx = w;
4128     surface->ds_current_size.cy = h;
4129     surface->Flags &= ~SFLAG_DS_LOCATIONS;
4130     surface->Flags |= location;
4131 }
4132
4133 /* Context activation is done by the caller. */
4134 void surface_load_ds_location(IWineD3DSurfaceImpl *surface, struct wined3d_context *context, DWORD location)
4135 {
4136     IWineD3DDeviceImpl *device = surface->resource.device;
4137     const struct wined3d_gl_info *gl_info = context->gl_info;
4138
4139     TRACE("surface %p, new location %#x.\n", surface, location);
4140
4141     /* TODO: Make this work for modes other than FBO */
4142     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return;
4143
4144     if (!(surface->Flags & location))
4145     {
4146         surface->ds_current_size.cx = 0;
4147         surface->ds_current_size.cy = 0;
4148     }
4149
4150     if (surface->ds_current_size.cx == surface->currentDesc.Width
4151             && surface->ds_current_size.cy == surface->currentDesc.Height)
4152     {
4153         TRACE("Location (%#x) is already up to date.\n", location);
4154         return;
4155     }
4156
4157     if (surface->current_renderbuffer)
4158     {
4159         FIXME("Not supported with fixed up depth stencil.\n");
4160         return;
4161     }
4162
4163     if (!(surface->Flags & SFLAG_LOCATIONS))
4164     {
4165         FIXME("No up to date depth stencil location.\n");
4166         surface->Flags |= location;
4167         return;
4168     }
4169
4170     if (location == SFLAG_DS_OFFSCREEN)
4171     {
4172         GLint old_binding = 0;
4173         GLenum bind_target;
4174         GLsizei w, h;
4175
4176         /* The render target is allowed to be smaller than the depth/stencil
4177          * buffer, so the onscreen depth/stencil buffer is potentially smaller
4178          * than the offscreen surface. Don't overwrite the offscreen surface
4179          * with undefined data. */
4180         w = min(surface->currentDesc.Width, context->swapchain->presentParms.BackBufferWidth);
4181         h = min(surface->currentDesc.Height, context->swapchain->presentParms.BackBufferHeight);
4182
4183         TRACE("Copying onscreen depth buffer to depth texture.\n");
4184
4185         ENTER_GL();
4186
4187         if (!device->depth_blt_texture)
4188         {
4189             glGenTextures(1, &device->depth_blt_texture);
4190         }
4191
4192         /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
4193          * directly on the FBO texture. That's because we need to flip. */
4194         context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4195         if (surface->texture_target == GL_TEXTURE_RECTANGLE_ARB)
4196         {
4197             glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
4198             bind_target = GL_TEXTURE_RECTANGLE_ARB;
4199         }
4200         else
4201         {
4202             glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
4203             bind_target = GL_TEXTURE_2D;
4204         }
4205         glBindTexture(bind_target, device->depth_blt_texture);
4206         glCopyTexImage2D(bind_target, surface->texture_level, surface->resource.format->glInternal, 0, 0, w, h, 0);
4207         glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4208         glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4209         glTexParameteri(bind_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
4210         glTexParameteri(bind_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
4211         glTexParameteri(bind_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
4212         glTexParameteri(bind_target, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
4213         glBindTexture(bind_target, old_binding);
4214
4215         /* Setup the destination */
4216         if (!device->depth_blt_rb)
4217         {
4218             gl_info->fbo_ops.glGenRenderbuffers(1, &device->depth_blt_rb);
4219             checkGLcall("glGenRenderbuffersEXT");
4220         }
4221         if (device->depth_blt_rb_w != w || device->depth_blt_rb_h != h)
4222         {
4223             gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, device->depth_blt_rb);
4224             checkGLcall("glBindRenderbufferEXT");
4225             gl_info->fbo_ops.glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, w, h);
4226             checkGLcall("glRenderbufferStorageEXT");
4227             device->depth_blt_rb_w = w;
4228             device->depth_blt_rb_h = h;
4229         }
4230
4231         context_bind_fbo(context, GL_FRAMEBUFFER, &context->dst_fbo);
4232         gl_info->fbo_ops.glFramebufferRenderbuffer(GL_FRAMEBUFFER,
4233                 GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, device->depth_blt_rb);
4234         checkGLcall("glFramebufferRenderbufferEXT");
4235         context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, surface, FALSE);
4236
4237         /* Do the actual blit */
4238         surface_depth_blt(surface, gl_info, device->depth_blt_texture, w, h, bind_target);
4239         checkGLcall("depth_blt");
4240
4241         if (context->current_fbo) context_bind_fbo(context, GL_FRAMEBUFFER, &context->current_fbo->id);
4242         else context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4243
4244         LEAVE_GL();
4245
4246         if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
4247     }
4248     else if (location == SFLAG_DS_ONSCREEN)
4249     {
4250         TRACE("Copying depth texture to onscreen depth buffer.\n");
4251
4252         ENTER_GL();
4253
4254         context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4255         surface_depth_blt(surface, gl_info, surface->texture_name,
4256                 surface->currentDesc.Width, surface->currentDesc.Height, surface->texture_target);
4257         checkGLcall("depth_blt");
4258
4259         if (context->current_fbo) context_bind_fbo(context, GL_FRAMEBUFFER, &context->current_fbo->id);
4260
4261         LEAVE_GL();
4262
4263         if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
4264     }
4265     else
4266     {
4267         ERR("Invalid location (%#x) specified.\n", location);
4268     }
4269
4270     surface->Flags |= location;
4271     surface->ds_current_size.cx = surface->currentDesc.Width;
4272     surface->ds_current_size.cy = surface->currentDesc.Height;
4273 }
4274
4275 void surface_modify_location(IWineD3DSurfaceImpl *surface, DWORD flag, BOOL persistent)
4276 {
4277     IWineD3DSurfaceImpl *overlay;
4278
4279     TRACE("surface %p, location %s, persistent %#x.\n",
4280             surface, debug_surflocation(flag), persistent);
4281
4282     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
4283     {
4284         if (surface_is_offscreen(surface))
4285         {
4286             /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4287             if (flag & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE)) flag |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4288         }
4289         else
4290         {
4291             TRACE("Surface %p is an onscreen surface.\n", surface);
4292         }
4293     }
4294
4295     if (persistent)
4296     {
4297         if (((surface->Flags & SFLAG_INTEXTURE) && !(flag & SFLAG_INTEXTURE))
4298                 || ((surface->Flags & SFLAG_INSRGBTEX) && !(flag & SFLAG_INSRGBTEX)))
4299         {
4300             if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
4301             {
4302                 TRACE("Passing to container.\n");
4303                 IWineD3DBaseTexture_SetDirty((IWineD3DBaseTexture *)surface->container.u.texture, TRUE);
4304             }
4305         }
4306         surface->Flags &= ~SFLAG_LOCATIONS;
4307         surface->Flags |= flag;
4308
4309         /* Redraw emulated overlays, if any */
4310         if (flag & SFLAG_INDRAWABLE && !list_empty(&surface->overlays))
4311         {
4312             LIST_FOR_EACH_ENTRY(overlay, &surface->overlays, IWineD3DSurfaceImpl, overlay_entry)
4313             {
4314                 IWineD3DSurface_DrawOverlay((IWineD3DSurface *)overlay);
4315             }
4316         }
4317     }
4318     else
4319     {
4320         if ((surface->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) && (flag & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)))
4321         {
4322             if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
4323             {
4324                 TRACE("Passing to container\n");
4325                 IWineD3DBaseTexture_SetDirty((IWineD3DBaseTexture *)surface->container.u.texture, TRUE);
4326             }
4327         }
4328         surface->Flags &= ~flag;
4329     }
4330
4331     if (!(surface->Flags & SFLAG_LOCATIONS))
4332     {
4333         ERR("Surface %p does not have any up to date location.\n", surface);
4334     }
4335 }
4336
4337 static inline void surface_blt_to_drawable(IWineD3DSurfaceImpl *This, const RECT *rect_in)
4338 {
4339     IWineD3DDeviceImpl *device = This->resource.device;
4340     IWineD3DSwapChainImpl *swapchain;
4341     struct wined3d_context *context;
4342     RECT src_rect, dst_rect;
4343
4344     surface_get_rect(This, rect_in, &src_rect);
4345
4346     context = context_acquire(device, This);
4347     context_apply_blit_state(context, device);
4348     if (context->render_offscreen)
4349     {
4350         dst_rect.left = src_rect.left;
4351         dst_rect.right = src_rect.right;
4352         dst_rect.top = src_rect.bottom;
4353         dst_rect.bottom = src_rect.top;
4354     }
4355     else
4356     {
4357         dst_rect = src_rect;
4358     }
4359
4360     swapchain = This->container.type == WINED3D_CONTAINER_SWAPCHAIN ? This->container.u.swapchain : NULL;
4361     if (swapchain && This == swapchain->front_buffer)
4362         surface_translate_frontbuffer_coords(This, context->win_handle, &dst_rect);
4363
4364     device->blitter->set_shader((IWineD3DDevice *) device, This);
4365
4366     ENTER_GL();
4367     draw_textured_quad(This, &src_rect, &dst_rect, WINED3DTEXF_POINT);
4368     LEAVE_GL();
4369
4370     device->blitter->unset_shader((IWineD3DDevice *) device);
4371
4372     if (wined3d_settings.strict_draw_ordering || (swapchain
4373             && (This == swapchain->front_buffer || swapchain->num_contexts > 1)))
4374         wglFlush(); /* Flush to ensure ordering across contexts. */
4375
4376     context_release(context);
4377 }
4378
4379 HRESULT surface_load_location(IWineD3DSurfaceImpl *surface, DWORD flag, const RECT *rect)
4380 {
4381     IWineD3DDeviceImpl *device = surface->resource.device;
4382     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4383     BOOL drawable_read_ok = surface_is_offscreen(surface);
4384     struct wined3d_format format;
4385     CONVERT_TYPES convert;
4386     int width, pitch, outpitch;
4387     BYTE *mem;
4388     BOOL in_fbo = FALSE;
4389
4390     TRACE("surface %p, location %s, rect %s.\n", surface, debug_surflocation(flag), wine_dbgstr_rect(rect));
4391
4392     if (surface->resource.usage & WINED3DUSAGE_DEPTHSTENCIL)
4393     {
4394         if (flag == SFLAG_INTEXTURE)
4395         {
4396             struct wined3d_context *context = context_acquire(device, NULL);
4397             surface_load_ds_location(surface, context, SFLAG_DS_OFFSCREEN);
4398             context_release(context);
4399             return WINED3D_OK;
4400         }
4401         else
4402         {
4403             FIXME("Unimplemented location %s for depth/stencil buffers.\n", debug_surflocation(flag));
4404             return WINED3DERR_INVALIDCALL;
4405         }
4406     }
4407
4408     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
4409     {
4410         if (surface_is_offscreen(surface))
4411         {
4412             /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets.
4413              * Prefer SFLAG_INTEXTURE. */
4414             if (flag == SFLAG_INDRAWABLE) flag = SFLAG_INTEXTURE;
4415             drawable_read_ok = FALSE;
4416             in_fbo = TRUE;
4417         }
4418         else
4419         {
4420             TRACE("Surface %p is an onscreen surface.\n", surface);
4421         }
4422     }
4423
4424     if (surface->Flags & flag)
4425     {
4426         TRACE("Location already up to date\n");
4427         return WINED3D_OK;
4428     }
4429
4430     if (!(surface->Flags & SFLAG_LOCATIONS))
4431     {
4432         ERR("Surface %p does not have any up to date location.\n", surface);
4433         surface->Flags |= SFLAG_LOST;
4434         return WINED3DERR_DEVICELOST;
4435     }
4436
4437     if (flag == SFLAG_INSYSMEM)
4438     {
4439         surface_prepare_system_memory(surface);
4440
4441         /* Download the surface to system memory */
4442         if (surface->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX))
4443         {
4444             struct wined3d_context *context = NULL;
4445
4446             if (!device->isInDraw) context = context_acquire(device, NULL);
4447
4448             surface_bind_and_dirtify(surface, !(surface->Flags & SFLAG_INTEXTURE));
4449             surface_download_data(surface, gl_info);
4450
4451             if (context) context_release(context);
4452         }
4453         else
4454         {
4455             /* Note: It might be faster to download into a texture first. */
4456             read_from_framebuffer(surface, rect, surface->resource.allocatedMemory,
4457                     IWineD3DSurface_GetPitch((IWineD3DSurface *)surface));
4458         }
4459     }
4460     else if (flag == SFLAG_INDRAWABLE)
4461     {
4462         if (surface->Flags & SFLAG_INTEXTURE)
4463         {
4464             surface_blt_to_drawable(surface, rect);
4465         }
4466         else
4467         {
4468             int byte_count;
4469             if ((surface->Flags & SFLAG_LOCATIONS) == SFLAG_INSRGBTEX)
4470             {
4471                 /* This needs a shader to convert the srgb data sampled from the GL texture into RGB
4472                  * values, otherwise we get incorrect values in the target. For now go the slow way
4473                  * via a system memory copy
4474                  */
4475                 surface_load_location(surface, SFLAG_INSYSMEM, rect);
4476             }
4477
4478             d3dfmt_get_conv(surface, FALSE /* We need color keying */,
4479                     FALSE /* We won't use textures */, &format, &convert);
4480
4481             /* The width is in 'length' not in bytes */
4482             width = surface->currentDesc.Width;
4483             pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *)surface);
4484
4485             /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4486              * but it isn't set (yet) in all cases it is getting called. */
4487             if ((convert != NO_CONVERSION) && (surface->Flags & SFLAG_PBO))
4488             {
4489                 struct wined3d_context *context = NULL;
4490
4491                 TRACE("Removing the pbo attached to surface %p.\n", surface);
4492
4493                 if (!device->isInDraw) context = context_acquire(device, NULL);
4494                 surface_remove_pbo(surface, gl_info);
4495                 if (context) context_release(context);
4496             }
4497
4498             if ((convert != NO_CONVERSION) && surface->resource.allocatedMemory)
4499             {
4500                 int height = surface->currentDesc.Height;
4501                 byte_count = format.conv_byte_count;
4502
4503                 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4504                 outpitch = width * byte_count;
4505                 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4506
4507                 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4508                 if(!mem) {
4509                     ERR("Out of memory %d, %d!\n", outpitch, height);
4510                     return WINED3DERR_OUTOFVIDEOMEMORY;
4511                 }
4512                 d3dfmt_convert_surface(surface->resource.allocatedMemory, mem, pitch,
4513                         width, height, outpitch, convert, surface);
4514
4515                 surface->Flags |= SFLAG_CONVERTED;
4516             }
4517             else
4518             {
4519                 surface->Flags &= ~SFLAG_CONVERTED;
4520                 mem = surface->resource.allocatedMemory;
4521                 byte_count = format.byte_count;
4522             }
4523
4524             flush_to_framebuffer_drawpixels(surface, format.glFormat, format.glType, byte_count, mem);
4525
4526             /* Don't delete PBO memory */
4527             if ((mem != surface->resource.allocatedMemory) && !(surface->Flags & SFLAG_PBO))
4528                 HeapFree(GetProcessHeap(), 0, mem);
4529         }
4530     }
4531     else /* if(flag & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) */
4532     {
4533         const DWORD attach_flags = WINED3DFMT_FLAG_FBO_ATTACHABLE | WINED3DFMT_FLAG_FBO_ATTACHABLE_SRGB;
4534
4535         if (drawable_read_ok && (surface->Flags & SFLAG_INDRAWABLE))
4536         {
4537             read_from_framebuffer_texture(surface, flag == SFLAG_INSRGBTEX);
4538         }
4539         else if (surface->Flags & (SFLAG_INSRGBTEX | SFLAG_INTEXTURE)
4540                 && (surface->resource.format->Flags & attach_flags) == attach_flags
4541                 && fbo_blit_supported(gl_info, BLIT_OP_BLIT,
4542                         NULL, surface->resource.usage, surface->resource.pool, surface->resource.format,
4543                         NULL, surface->resource.usage, surface->resource.pool, surface->resource.format))
4544         {
4545             DWORD src_location = flag == SFLAG_INSRGBTEX ? SFLAG_INTEXTURE : SFLAG_INSRGBTEX;
4546             RECT rect = {0, 0, surface->currentDesc.Width, surface->currentDesc.Height};
4547
4548             surface_blt_fbo(surface->resource.device, WINED3DTEXF_POINT,
4549                     surface, src_location, &rect, surface, flag, &rect);
4550         }
4551         else
4552         {
4553             /* Upload from system memory */
4554             BOOL srgb = flag == SFLAG_INSRGBTEX;
4555             struct wined3d_context *context = NULL;
4556
4557             d3dfmt_get_conv(surface, TRUE /* We need color keying */,
4558                     TRUE /* We will use textures */, &format, &convert);
4559
4560             if (srgb)
4561             {
4562                 if ((surface->Flags & (SFLAG_INTEXTURE | SFLAG_INSYSMEM)) == SFLAG_INTEXTURE)
4563                 {
4564                     /* Performance warning... */
4565                     FIXME("Downloading RGB surface %p to reload it as sRGB.\n", surface);
4566                     surface_load_location(surface, SFLAG_INSYSMEM, rect);
4567                 }
4568             }
4569             else
4570             {
4571                 if ((surface->Flags & (SFLAG_INSRGBTEX | SFLAG_INSYSMEM)) == SFLAG_INSRGBTEX)
4572                 {
4573                     /* Performance warning... */
4574                     FIXME("Downloading sRGB surface %p to reload it as RGB.\n", surface);
4575                     surface_load_location(surface, SFLAG_INSYSMEM, rect);
4576                 }
4577             }
4578             if (!(surface->Flags & SFLAG_INSYSMEM))
4579             {
4580                 WARN("Trying to load a texture from sysmem, but SFLAG_INSYSMEM is not set.\n");
4581                 /* Lets hope we get it from somewhere... */
4582                 surface_load_location(surface, SFLAG_INSYSMEM, rect);
4583             }
4584
4585             if (!device->isInDraw) context = context_acquire(device, NULL);
4586
4587             surface_prepare_texture(surface, gl_info, srgb);
4588             surface_bind_and_dirtify(surface, srgb);
4589
4590             if (surface->CKeyFlags & WINEDDSD_CKSRCBLT)
4591             {
4592                 surface->Flags |= SFLAG_GLCKEY;
4593                 surface->glCKey = surface->SrcBltCKey;
4594             }
4595             else surface->Flags &= ~SFLAG_GLCKEY;
4596
4597             /* The width is in 'length' not in bytes */
4598             width = surface->currentDesc.Width;
4599             pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *)surface);
4600
4601             /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4602              * but it isn't set (yet) in all cases it is getting called. */
4603             if ((convert != NO_CONVERSION || format.convert) && (surface->Flags & SFLAG_PBO))
4604             {
4605                 TRACE("Removing the pbo attached to surface %p.\n", surface);
4606                 surface_remove_pbo(surface, gl_info);
4607             }
4608
4609             if (format.convert)
4610             {
4611                 /* This code is entered for texture formats which need a fixup. */
4612                 int height = surface->currentDesc.Height;
4613
4614                 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4615                 outpitch = width * format.conv_byte_count;
4616                 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4617
4618                 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4619                 if(!mem) {
4620                     ERR("Out of memory %d, %d!\n", outpitch, height);
4621                     if (context) context_release(context);
4622                     return WINED3DERR_OUTOFVIDEOMEMORY;
4623                 }
4624                 format.convert(surface->resource.allocatedMemory, mem, pitch, width, height);
4625             }
4626             else if (convert != NO_CONVERSION && surface->resource.allocatedMemory)
4627             {
4628                 /* This code is only entered for color keying fixups */
4629                 int height = surface->currentDesc.Height;
4630
4631                 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4632                 outpitch = width * format.conv_byte_count;
4633                 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4634
4635                 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4636                 if(!mem) {
4637                     ERR("Out of memory %d, %d!\n", outpitch, height);
4638                     if (context) context_release(context);
4639                     return WINED3DERR_OUTOFVIDEOMEMORY;
4640                 }
4641                 d3dfmt_convert_surface(surface->resource.allocatedMemory, mem, pitch,
4642                         width, height, outpitch, convert, surface);
4643             }
4644             else
4645             {
4646                 mem = surface->resource.allocatedMemory;
4647             }
4648
4649             /* Make sure the correct pitch is used */
4650             ENTER_GL();
4651             glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
4652             LEAVE_GL();
4653
4654             if (mem || (surface->Flags & SFLAG_PBO))
4655                 surface_upload_data(surface, gl_info, &format, srgb, mem);
4656
4657             /* Restore the default pitch */
4658             ENTER_GL();
4659             glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
4660             LEAVE_GL();
4661
4662             if (context) context_release(context);
4663
4664             /* Don't delete PBO memory */
4665             if ((mem != surface->resource.allocatedMemory) && !(surface->Flags & SFLAG_PBO))
4666                 HeapFree(GetProcessHeap(), 0, mem);
4667         }
4668     }
4669
4670     if (!rect) surface->Flags |= flag;
4671
4672     if (in_fbo && (surface->Flags & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE)))
4673     {
4674         /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4675         surface->Flags |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4676     }
4677
4678     return WINED3D_OK;
4679 }
4680
4681 static WINED3DSURFTYPE WINAPI IWineD3DSurfaceImpl_GetImplType(IWineD3DSurface *iface) {
4682     return SURFACE_OPENGL;
4683 }
4684
4685 static HRESULT WINAPI IWineD3DSurfaceImpl_DrawOverlay(IWineD3DSurface *iface) {
4686     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4687     HRESULT hr;
4688
4689     /* If there's no destination surface there is nothing to do */
4690     if(!This->overlay_dest) return WINED3D_OK;
4691
4692     /* Blt calls ModifyLocation on the dest surface, which in turn calls DrawOverlay to
4693      * update the overlay. Prevent an endless recursion
4694      */
4695     if(This->overlay_dest->Flags & SFLAG_INOVERLAYDRAW) {
4696         return WINED3D_OK;
4697     }
4698     This->overlay_dest->Flags |= SFLAG_INOVERLAYDRAW;
4699     hr = IWineD3DSurfaceImpl_Blt((IWineD3DSurface *) This->overlay_dest, &This->overlay_destrect,
4700                                  iface, &This->overlay_srcrect, WINEDDBLT_WAIT,
4701                                  NULL, WINED3DTEXF_LINEAR);
4702     This->overlay_dest->Flags &= ~SFLAG_INOVERLAYDRAW;
4703
4704     return hr;
4705 }
4706
4707 BOOL surface_is_offscreen(IWineD3DSurfaceImpl *surface)
4708 {
4709     IWineD3DSwapChainImpl *swapchain = surface->container.u.swapchain;
4710
4711     /* Not on a swapchain - must be offscreen */
4712     if (surface->container.type != WINED3D_CONTAINER_SWAPCHAIN) return TRUE;
4713
4714     /* The front buffer is always onscreen */
4715     if (surface == swapchain->front_buffer) return FALSE;
4716
4717     /* If the swapchain is rendered to an FBO, the backbuffer is
4718      * offscreen, otherwise onscreen */
4719     return swapchain->render_to_fbo;
4720 }
4721
4722 const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl =
4723 {
4724     /* IUnknown */
4725     IWineD3DBaseSurfaceImpl_QueryInterface,
4726     IWineD3DBaseSurfaceImpl_AddRef,
4727     IWineD3DSurfaceImpl_Release,
4728     /* IWineD3DResource */
4729     IWineD3DBaseSurfaceImpl_GetParent,
4730     IWineD3DBaseSurfaceImpl_SetPrivateData,
4731     IWineD3DBaseSurfaceImpl_GetPrivateData,
4732     IWineD3DBaseSurfaceImpl_FreePrivateData,
4733     IWineD3DBaseSurfaceImpl_SetPriority,
4734     IWineD3DBaseSurfaceImpl_GetPriority,
4735     IWineD3DSurfaceImpl_PreLoad,
4736     IWineD3DSurfaceImpl_UnLoad,
4737     IWineD3DBaseSurfaceImpl_GetType,
4738     /* IWineD3DSurface */
4739     IWineD3DBaseSurfaceImpl_GetDesc,
4740     IWineD3DSurfaceImpl_Map,
4741     IWineD3DSurfaceImpl_Unmap,
4742     IWineD3DSurfaceImpl_GetDC,
4743     IWineD3DSurfaceImpl_ReleaseDC,
4744     IWineD3DSurfaceImpl_Flip,
4745     IWineD3DSurfaceImpl_Blt,
4746     IWineD3DBaseSurfaceImpl_GetBltStatus,
4747     IWineD3DBaseSurfaceImpl_GetFlipStatus,
4748     IWineD3DBaseSurfaceImpl_IsLost,
4749     IWineD3DBaseSurfaceImpl_Restore,
4750     IWineD3DSurfaceImpl_BltFast,
4751     IWineD3DBaseSurfaceImpl_GetPalette,
4752     IWineD3DBaseSurfaceImpl_SetPalette,
4753     IWineD3DSurfaceImpl_RealizePalette,
4754     IWineD3DBaseSurfaceImpl_SetColorKey,
4755     IWineD3DBaseSurfaceImpl_GetPitch,
4756     IWineD3DSurfaceImpl_SetMem,
4757     IWineD3DBaseSurfaceImpl_SetOverlayPosition,
4758     IWineD3DBaseSurfaceImpl_GetOverlayPosition,
4759     IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder,
4760     IWineD3DBaseSurfaceImpl_UpdateOverlay,
4761     IWineD3DBaseSurfaceImpl_SetClipper,
4762     IWineD3DBaseSurfaceImpl_GetClipper,
4763     /* Internal use: */
4764     IWineD3DSurfaceImpl_LoadTexture,
4765     IWineD3DSurfaceImpl_BindTexture,
4766     IWineD3DBaseSurfaceImpl_GetData,
4767     IWineD3DSurfaceImpl_SetFormat,
4768     IWineD3DSurfaceImpl_PrivateSetup,
4769     IWineD3DSurfaceImpl_GetImplType,
4770     IWineD3DSurfaceImpl_DrawOverlay
4771 };
4772
4773 static HRESULT ffp_blit_alloc(IWineD3DDevice *iface) { return WINED3D_OK; }
4774 /* Context activation is done by the caller. */
4775 static void ffp_blit_free(IWineD3DDevice *iface) { }
4776
4777 /* This function is used in case of 8bit paletted textures using GL_EXT_paletted_texture */
4778 /* Context activation is done by the caller. */
4779 static void ffp_blit_p8_upload_palette(IWineD3DSurfaceImpl *surface, const struct wined3d_gl_info *gl_info)
4780 {
4781     BYTE table[256][4];
4782     BOOL colorkey_active = (surface->CKeyFlags & WINEDDSD_CKSRCBLT) ? TRUE : FALSE;
4783
4784     d3dfmt_p8_init_palette(surface, table, colorkey_active);
4785
4786     TRACE("Using GL_EXT_PALETTED_TEXTURE for 8-bit paletted texture support\n");
4787     ENTER_GL();
4788     GL_EXTCALL(glColorTableEXT(surface->texture_target, GL_RGBA, 256, GL_RGBA, GL_UNSIGNED_BYTE, table));
4789     LEAVE_GL();
4790 }
4791
4792 /* Context activation is done by the caller. */
4793 static HRESULT ffp_blit_set(IWineD3DDevice *iface, IWineD3DSurfaceImpl *surface)
4794 {
4795     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
4796     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4797     enum complex_fixup fixup = get_complex_fixup(surface->resource.format->color_fixup);
4798
4799     /* When EXT_PALETTED_TEXTURE is around, palette conversion is done by the GPU
4800      * else the surface is converted in software at upload time in LoadLocation.
4801      */
4802     if(fixup == COMPLEX_FIXUP_P8 && gl_info->supported[EXT_PALETTED_TEXTURE])
4803         ffp_blit_p8_upload_palette(surface, gl_info);
4804
4805     ENTER_GL();
4806     glEnable(surface->texture_target);
4807     checkGLcall("glEnable(surface->texture_target)");
4808     LEAVE_GL();
4809     return WINED3D_OK;
4810 }
4811
4812 /* Context activation is done by the caller. */
4813 static void ffp_blit_unset(IWineD3DDevice *iface)
4814 {
4815     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
4816     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4817
4818     ENTER_GL();
4819     glDisable(GL_TEXTURE_2D);
4820     checkGLcall("glDisable(GL_TEXTURE_2D)");
4821     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
4822     {
4823         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
4824         checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
4825     }
4826     if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4827     {
4828         glDisable(GL_TEXTURE_RECTANGLE_ARB);
4829         checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
4830     }
4831     LEAVE_GL();
4832 }
4833
4834 static BOOL ffp_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4835         const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool, const struct wined3d_format *src_format,
4836         const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool, const struct wined3d_format *dst_format)
4837 {
4838     enum complex_fixup src_fixup;
4839
4840     if (blit_op == BLIT_OP_COLOR_FILL)
4841     {
4842         if (!(dst_usage & WINED3DUSAGE_RENDERTARGET))
4843         {
4844             TRACE("Color fill not supported\n");
4845             return FALSE;
4846         }
4847
4848         return TRUE;
4849     }
4850
4851     src_fixup = get_complex_fixup(src_format->color_fixup);
4852     if (TRACE_ON(d3d_surface) && TRACE_ON(d3d))
4853     {
4854         TRACE("Checking support for fixup:\n");
4855         dump_color_fixup_desc(src_format->color_fixup);
4856     }
4857
4858     if (blit_op != BLIT_OP_BLIT)
4859     {
4860         TRACE("Unsupported blit_op=%d\n", blit_op);
4861         return FALSE;
4862      }
4863
4864     if (!is_identity_fixup(dst_format->color_fixup))
4865     {
4866         TRACE("Destination fixups are not supported\n");
4867         return FALSE;
4868     }
4869
4870     if (src_fixup == COMPLEX_FIXUP_P8 && gl_info->supported[EXT_PALETTED_TEXTURE])
4871     {
4872         TRACE("P8 fixup supported\n");
4873         return TRUE;
4874     }
4875
4876     /* We only support identity conversions. */
4877     if (is_identity_fixup(src_format->color_fixup))
4878     {
4879         TRACE("[OK]\n");
4880         return TRUE;
4881     }
4882
4883     TRACE("[FAILED]\n");
4884     return FALSE;
4885 }
4886
4887 /* Do not call while under the GL lock. */
4888 static HRESULT ffp_blit_color_fill(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *dst_surface,
4889         const RECT *dst_rect, const WINED3DCOLORVALUE *color)
4890 {
4891     const RECT draw_rect = {0, 0, dst_surface->currentDesc.Width, dst_surface->currentDesc.Height};
4892
4893     return device_clear_render_targets(device, 1 /* rt_count */, &dst_surface, 1 /* rect_count */,
4894             dst_rect, &draw_rect, WINED3DCLEAR_TARGET, color, 0.0f /* depth */, 0 /* stencil */);
4895 }
4896
4897 const struct blit_shader ffp_blit =  {
4898     ffp_blit_alloc,
4899     ffp_blit_free,
4900     ffp_blit_set,
4901     ffp_blit_unset,
4902     ffp_blit_supported,
4903     ffp_blit_color_fill
4904 };
4905
4906 static HRESULT cpu_blit_alloc(IWineD3DDevice *iface)
4907 {
4908     return WINED3D_OK;
4909 }
4910
4911 /* Context activation is done by the caller. */
4912 static void cpu_blit_free(IWineD3DDevice *iface)
4913 {
4914 }
4915
4916 /* Context activation is done by the caller. */
4917 static HRESULT cpu_blit_set(IWineD3DDevice *iface, IWineD3DSurfaceImpl *surface)
4918 {
4919     return WINED3D_OK;
4920 }
4921
4922 /* Context activation is done by the caller. */
4923 static void cpu_blit_unset(IWineD3DDevice *iface)
4924 {
4925 }
4926
4927 static BOOL cpu_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4928         const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool, const struct wined3d_format *src_format,
4929         const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool, const struct wined3d_format *dst_format)
4930 {
4931     if (blit_op == BLIT_OP_COLOR_FILL)
4932     {
4933         return TRUE;
4934     }
4935
4936     return FALSE;
4937 }
4938
4939 /* Do not call while under the GL lock. */
4940 static HRESULT cpu_blit_color_fill(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *dst_surface,
4941         const RECT *dst_rect, const WINED3DCOLORVALUE *color)
4942 {
4943     WINEDDBLTFX BltFx;
4944
4945     memset(&BltFx, 0, sizeof(BltFx));
4946     BltFx.dwSize = sizeof(BltFx);
4947     BltFx.u5.dwFillColor = wined3d_format_convert_from_float(dst_surface->resource.format, color);
4948     return IWineD3DBaseSurfaceImpl_Blt((IWineD3DSurface*)dst_surface, dst_rect,
4949             NULL, NULL, WINEDDBLT_COLORFILL, &BltFx, WINED3DTEXF_POINT);
4950 }
4951
4952 const struct blit_shader cpu_blit =  {
4953     cpu_blit_alloc,
4954     cpu_blit_free,
4955     cpu_blit_set,
4956     cpu_blit_unset,
4957     cpu_blit_supported,
4958     cpu_blit_color_fill
4959 };
4960
4961 static BOOL fbo_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4962         const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool, const struct wined3d_format *src_format,
4963         const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool, const struct wined3d_format *dst_format)
4964 {
4965     if ((wined3d_settings.offscreen_rendering_mode != ORM_FBO) || !gl_info->fbo_ops.glBlitFramebuffer)
4966         return FALSE;
4967
4968     /* We only support blitting. Things like color keying / color fill should
4969      * be handled by other blitters.
4970      */
4971     if (blit_op != BLIT_OP_BLIT)
4972         return FALSE;
4973
4974     /* Source and/or destination need to be on the GL side */
4975     if (src_pool == WINED3DPOOL_SYSTEMMEM || dst_pool == WINED3DPOOL_SYSTEMMEM)
4976         return FALSE;
4977
4978     if (!((src_format->Flags & WINED3DFMT_FLAG_FBO_ATTACHABLE) || (src_usage & WINED3DUSAGE_RENDERTARGET))
4979             && ((dst_format->Flags & WINED3DFMT_FLAG_FBO_ATTACHABLE) || (dst_usage & WINED3DUSAGE_RENDERTARGET)))
4980         return FALSE;
4981
4982     if (!(src_format->id == dst_format->id
4983             || (is_identity_fixup(src_format->color_fixup)
4984             && is_identity_fixup(dst_format->color_fixup))))
4985         return FALSE;
4986
4987     return TRUE;
4988 }