2 * IWineD3DSurface Implementation
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
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.
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.
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
31 #include "wine/port.h"
32 #include "wined3d_private.h"
34 WINE_DEFAULT_DEBUG_CHANNEL(d3d_surface);
35 WINE_DECLARE_DEBUG_CHANNEL(d3d);
37 static void surface_cleanup(IWineD3DSurfaceImpl *This)
39 TRACE("(%p) : Cleaning up.\n", This);
41 if (This->texture_name || (This->Flags & SFLAG_PBO) || !list_empty(&This->renderbuffers))
43 const struct wined3d_gl_info *gl_info;
44 renderbuffer_entry_t *entry, *entry2;
45 struct wined3d_context *context;
47 context = context_acquire(This->resource.device, NULL);
48 gl_info = context->gl_info;
52 if (This->texture_name)
54 TRACE("Deleting texture %u.\n", This->texture_name);
55 glDeleteTextures(1, &This->texture_name);
58 if (This->Flags & SFLAG_PBO)
60 TRACE("Deleting PBO %u.\n", This->pbo);
61 GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
64 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry)
66 TRACE("Deleting renderbuffer %u.\n", entry->id);
67 gl_info->fbo_ops.glDeleteRenderbuffers(1, &entry->id);
68 HeapFree(GetProcessHeap(), 0, entry);
73 context_release(context);
76 if (This->Flags & SFLAG_DIBSECTION)
79 SelectObject(This->hDC, This->dib.holdbitmap);
81 /* Release the DIB section. */
82 DeleteObject(This->dib.DIBsection);
83 This->dib.bitmap_data = NULL;
84 This->resource.allocatedMemory = NULL;
87 if (This->Flags & SFLAG_USERPTR) IWineD3DSurface_SetMem((IWineD3DSurface *)This, NULL);
88 if (This->overlay_dest) list_remove(&This->overlay_entry);
90 HeapFree(GetProcessHeap(), 0, This->palette9);
92 resource_cleanup((IWineD3DResource *)This);
95 void surface_set_container(IWineD3DSurfaceImpl *surface, enum wined3d_container_type type, IWineD3DBase *container)
97 TRACE("surface %p, container %p.\n", surface, container);
99 if (!container && type != WINED3D_CONTAINER_NONE)
100 ERR("Setting NULL container of type %#x.\n", type);
102 if (type == WINED3D_CONTAINER_SWAPCHAIN)
104 surface->get_drawable_size = get_drawable_size_swapchain;
108 switch (wined3d_settings.offscreen_rendering_mode)
111 surface->get_drawable_size = get_drawable_size_fbo;
115 surface->get_drawable_size = get_drawable_size_backbuffer;
119 ERR("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
124 surface->container.type = type;
125 surface->container.u.base = container;
132 enum tex_types tex_type;
133 GLfloat coords[4][3];
144 static inline void cube_coords_float(const RECT *r, UINT w, UINT h, struct float_rect *f)
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;
152 static void surface_get_blt_info(GLenum target, const RECT *rect, GLsizei w, GLsizei h, struct blt_info *info)
154 GLfloat (*coords)[3] = info->coords;
160 FIXME("Unsupported texture target %#x\n", target);
161 /* Fall back to GL_TEXTURE_2D */
163 info->binding = GL_TEXTURE_BINDING_2D;
164 info->bind_target = GL_TEXTURE_2D;
165 info->tex_type = tex_2d;
166 coords[0][0] = (float)rect->left / w;
167 coords[0][1] = (float)rect->top / h;
170 coords[1][0] = (float)rect->right / w;
171 coords[1][1] = (float)rect->top / h;
174 coords[2][0] = (float)rect->left / w;
175 coords[2][1] = (float)rect->bottom / h;
178 coords[3][0] = (float)rect->right / w;
179 coords[3][1] = (float)rect->bottom / h;
183 case GL_TEXTURE_RECTANGLE_ARB:
184 info->binding = GL_TEXTURE_BINDING_RECTANGLE_ARB;
185 info->bind_target = GL_TEXTURE_RECTANGLE_ARB;
186 info->tex_type = tex_rect;
187 coords[0][0] = rect->left; coords[0][1] = rect->top; coords[0][2] = 0.0f;
188 coords[1][0] = rect->right; coords[1][1] = rect->top; coords[1][2] = 0.0f;
189 coords[2][0] = rect->left; coords[2][1] = rect->bottom; coords[2][2] = 0.0f;
190 coords[3][0] = rect->right; coords[3][1] = rect->bottom; coords[3][2] = 0.0f;
193 case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
194 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
195 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
196 info->tex_type = tex_cube;
197 cube_coords_float(rect, w, h, &f);
199 coords[0][0] = 1.0f; coords[0][1] = -f.t; coords[0][2] = -f.l;
200 coords[1][0] = 1.0f; coords[1][1] = -f.t; coords[1][2] = -f.r;
201 coords[2][0] = 1.0f; coords[2][1] = -f.b; coords[2][2] = -f.l;
202 coords[3][0] = 1.0f; coords[3][1] = -f.b; coords[3][2] = -f.r;
205 case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
206 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
207 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
208 info->tex_type = tex_cube;
209 cube_coords_float(rect, w, h, &f);
211 coords[0][0] = -1.0f; coords[0][1] = -f.t; coords[0][2] = f.l;
212 coords[1][0] = -1.0f; coords[1][1] = -f.t; coords[1][2] = f.r;
213 coords[2][0] = -1.0f; coords[2][1] = -f.b; coords[2][2] = f.l;
214 coords[3][0] = -1.0f; coords[3][1] = -f.b; coords[3][2] = f.r;
217 case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
218 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
219 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
220 info->tex_type = tex_cube;
221 cube_coords_float(rect, w, h, &f);
223 coords[0][0] = f.l; coords[0][1] = 1.0f; coords[0][2] = f.t;
224 coords[1][0] = f.r; coords[1][1] = 1.0f; coords[1][2] = f.t;
225 coords[2][0] = f.l; coords[2][1] = 1.0f; coords[2][2] = f.b;
226 coords[3][0] = f.r; coords[3][1] = 1.0f; coords[3][2] = f.b;
229 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
230 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
231 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
232 info->tex_type = tex_cube;
233 cube_coords_float(rect, w, h, &f);
235 coords[0][0] = f.l; coords[0][1] = -1.0f; coords[0][2] = -f.t;
236 coords[1][0] = f.r; coords[1][1] = -1.0f; coords[1][2] = -f.t;
237 coords[2][0] = f.l; coords[2][1] = -1.0f; coords[2][2] = -f.b;
238 coords[3][0] = f.r; coords[3][1] = -1.0f; coords[3][2] = -f.b;
241 case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
242 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
243 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
244 info->tex_type = tex_cube;
245 cube_coords_float(rect, w, h, &f);
247 coords[0][0] = f.l; coords[0][1] = -f.t; coords[0][2] = 1.0f;
248 coords[1][0] = f.r; coords[1][1] = -f.t; coords[1][2] = 1.0f;
249 coords[2][0] = f.l; coords[2][1] = -f.b; coords[2][2] = 1.0f;
250 coords[3][0] = f.r; coords[3][1] = -f.b; coords[3][2] = 1.0f;
253 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
254 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
255 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
256 info->tex_type = tex_cube;
257 cube_coords_float(rect, w, h, &f);
259 coords[0][0] = -f.l; coords[0][1] = -f.t; coords[0][2] = -1.0f;
260 coords[1][0] = -f.r; coords[1][1] = -f.t; coords[1][2] = -1.0f;
261 coords[2][0] = -f.l; coords[2][1] = -f.b; coords[2][2] = -1.0f;
262 coords[3][0] = -f.r; coords[3][1] = -f.b; coords[3][2] = -1.0f;
267 static inline void surface_get_rect(IWineD3DSurfaceImpl *This, const RECT *rect_in, RECT *rect_out)
270 *rect_out = *rect_in;
275 rect_out->right = This->currentDesc.Width;
276 rect_out->bottom = This->currentDesc.Height;
280 /* GL locking and context activation is done by the caller */
281 void draw_textured_quad(IWineD3DSurfaceImpl *src_surface, const RECT *src_rect, const RECT *dst_rect, WINED3DTEXTUREFILTERTYPE Filter)
283 struct blt_info info;
285 surface_get_blt_info(src_surface->texture_target, src_rect, src_surface->pow2Width, src_surface->pow2Height, &info);
287 glEnable(info.bind_target);
288 checkGLcall("glEnable(bind_target)");
290 /* Bind the texture */
291 glBindTexture(info.bind_target, src_surface->texture_name);
292 checkGLcall("glBindTexture");
294 /* Filtering for StretchRect */
295 glTexParameteri(info.bind_target, GL_TEXTURE_MAG_FILTER,
296 wined3d_gl_mag_filter(magLookup, Filter));
297 checkGLcall("glTexParameteri");
298 glTexParameteri(info.bind_target, GL_TEXTURE_MIN_FILTER,
299 wined3d_gl_min_mip_filter(minMipLookup, Filter, WINED3DTEXF_NONE));
300 checkGLcall("glTexParameteri");
301 glTexParameteri(info.bind_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
302 glTexParameteri(info.bind_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
303 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
304 checkGLcall("glTexEnvi");
307 glBegin(GL_TRIANGLE_STRIP);
308 glTexCoord3fv(info.coords[0]);
309 glVertex2i(dst_rect->left, dst_rect->top);
311 glTexCoord3fv(info.coords[1]);
312 glVertex2i(dst_rect->right, dst_rect->top);
314 glTexCoord3fv(info.coords[2]);
315 glVertex2i(dst_rect->left, dst_rect->bottom);
317 glTexCoord3fv(info.coords[3]);
318 glVertex2i(dst_rect->right, dst_rect->bottom);
321 /* Unbind the texture */
322 glBindTexture(info.bind_target, 0);
323 checkGLcall("glBindTexture(info->bind_target, 0)");
325 /* We changed the filtering settings on the texture. Inform the
326 * container about this to get the filters reset properly next draw. */
327 if (src_surface->container.type == WINED3D_CONTAINER_TEXTURE)
329 IWineD3DBaseTextureImpl *texture = src_surface->container.u.texture;
330 texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
331 texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
332 texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
336 HRESULT surface_init(IWineD3DSurfaceImpl *surface, WINED3DSURFTYPE surface_type, UINT alignment,
337 UINT width, UINT height, UINT level, BOOL lockable, BOOL discard, WINED3DMULTISAMPLE_TYPE multisample_type,
338 UINT multisample_quality, IWineD3DDeviceImpl *device, DWORD usage, enum wined3d_format_id format_id,
339 WINED3DPOOL pool, void *parent, const struct wined3d_parent_ops *parent_ops)
341 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
342 const struct wined3d_format *format = wined3d_get_format(gl_info, format_id);
343 void (*cleanup)(IWineD3DSurfaceImpl *This);
344 unsigned int resource_size;
347 if (multisample_quality > 0)
349 FIXME("multisample_quality set to %u, substituting 0\n", multisample_quality);
350 multisample_quality = 0;
353 /* FIXME: Check that the format is supported by the device. */
355 resource_size = wined3d_format_calculate_size(format, alignment, width, height);
357 /* Look at the implementation and set the correct Vtable. */
358 switch (surface_type)
361 surface->lpVtbl = &IWineD3DSurface_Vtbl;
362 cleanup = surface_cleanup;
366 surface->lpVtbl = &IWineGDISurface_Vtbl;
367 cleanup = surface_gdi_cleanup;
371 ERR("Requested unknown surface implementation %#x.\n", surface_type);
372 return WINED3DERR_INVALIDCALL;
375 hr = resource_init((IWineD3DResource *)surface, WINED3DRTYPE_SURFACE,
376 device, resource_size, usage, format, pool, parent, parent_ops);
379 WARN("Failed to initialize resource, returning %#x.\n", hr);
383 /* "Standalone" surface. */
384 surface_set_container(surface, WINED3D_CONTAINER_NONE, NULL);
386 surface->currentDesc.Width = width;
387 surface->currentDesc.Height = height;
388 surface->currentDesc.MultiSampleType = multisample_type;
389 surface->currentDesc.MultiSampleQuality = multisample_quality;
390 surface->texture_level = level;
391 list_init(&surface->overlays);
394 surface->Flags = SFLAG_NORMCOORD; /* Default to normalized coords. */
395 if (discard) surface->Flags |= SFLAG_DISCARD;
396 if (lockable || format_id == WINED3DFMT_D16_LOCKABLE) surface->Flags |= SFLAG_LOCKABLE;
398 /* Quick lockable sanity check.
399 * TODO: remove this after surfaces, usage and lockability have been debugged properly
400 * this function is too deep to need to care about things like this.
401 * Levels need to be checked too, since they all affect what can be done. */
404 case WINED3DPOOL_SCRATCH:
407 FIXME("Called with a pool of SCRATCH and a lockable of FALSE "
408 "which are mutually exclusive, setting lockable to TRUE.\n");
413 case WINED3DPOOL_SYSTEMMEM:
415 FIXME("Called with a pool of SYSTEMMEM and a lockable of FALSE, this is acceptable but unexpected.\n");
418 case WINED3DPOOL_MANAGED:
419 if (usage & WINED3DUSAGE_DYNAMIC)
420 FIXME("Called with a pool of MANAGED and a usage of DYNAMIC which are mutually exclusive.\n");
423 case WINED3DPOOL_DEFAULT:
424 if (lockable && !(usage & (WINED3DUSAGE_DYNAMIC | WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL)))
425 WARN("Creating a lockable surface with a POOL of DEFAULT, that doesn't specify DYNAMIC usage.\n");
429 FIXME("Unknown pool %#x.\n", pool);
433 if (usage & WINED3DUSAGE_RENDERTARGET && pool != WINED3DPOOL_DEFAULT)
435 FIXME("Trying to create a render target that isn't in the default pool.\n");
438 /* Mark the texture as dirty so that it gets loaded first time around. */
439 surface_add_dirty_rect(surface, NULL);
440 list_init(&surface->renderbuffers);
442 TRACE("surface %p, memory %p, size %u\n", surface, surface->resource.allocatedMemory, surface->resource.size);
444 /* Call the private setup routine */
445 hr = IWineD3DSurface_PrivateSetup((IWineD3DSurface *)surface);
448 ERR("Private setup failed, returning %#x\n", hr);
456 static void surface_force_reload(IWineD3DSurfaceImpl *surface)
458 surface->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
461 void surface_set_texture_name(IWineD3DSurfaceImpl *surface, GLuint new_name, BOOL srgb)
466 TRACE("surface %p, new_name %u, srgb %#x.\n", surface, new_name, srgb);
470 name = &surface->texture_name_srgb;
471 flag = SFLAG_INSRGBTEX;
475 name = &surface->texture_name;
476 flag = SFLAG_INTEXTURE;
479 if (!*name && new_name)
481 /* FIXME: We shouldn't need to remove SFLAG_INTEXTURE if the
482 * surface has no texture name yet. See if we can get rid of this. */
483 if (surface->Flags & flag)
484 ERR("Surface has %s set, but no texture name.\n", debug_surflocation(flag));
485 surface_modify_location(surface, flag, FALSE);
489 surface_force_reload(surface);
492 void surface_set_texture_target(IWineD3DSurfaceImpl *surface, GLenum target)
494 TRACE("surface %p, target %#x.\n", surface, target);
496 if (surface->texture_target != target)
498 if (target == GL_TEXTURE_RECTANGLE_ARB)
500 surface->Flags &= ~SFLAG_NORMCOORD;
502 else if (surface->texture_target == GL_TEXTURE_RECTANGLE_ARB)
504 surface->Flags |= SFLAG_NORMCOORD;
507 surface->texture_target = target;
508 surface_force_reload(surface);
511 /* Context activation is done by the caller. */
512 static void surface_bind_and_dirtify(IWineD3DSurfaceImpl *This, BOOL srgb) {
513 DWORD active_sampler;
515 /* We don't need a specific texture unit, but after binding the texture the current unit is dirty.
516 * Read the unit back instead of switching to 0, this avoids messing around with the state manager's
517 * gl states. The current texture unit should always be a valid one.
519 * To be more specific, this is tricky because we can implicitly be called
520 * from sampler() in state.c. This means we can't touch anything other than
521 * whatever happens to be the currently active texture, or we would risk
522 * marking already applied sampler states dirty again.
524 * TODO: Track the current active texture per GL context instead of using glGet
526 GLint active_texture;
528 glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
530 active_sampler = This->resource.device->rev_tex_unit_map[active_texture - GL_TEXTURE0_ARB];
532 if (active_sampler != WINED3D_UNMAPPED_STAGE)
534 IWineD3DDeviceImpl_MarkStateDirty(This->resource.device, STATE_SAMPLER(active_sampler));
536 IWineD3DSurface_BindTexture((IWineD3DSurface *)This, srgb);
539 /* This function checks if the primary render target uses the 8bit paletted format. */
540 static BOOL primary_render_target_is_p8(IWineD3DDeviceImpl *device)
542 if (device->render_targets && device->render_targets[0])
544 IWineD3DSurfaceImpl *render_target = device->render_targets[0];
545 if ((render_target->resource.usage & WINED3DUSAGE_RENDERTARGET)
546 && (render_target->resource.format->id == WINED3DFMT_P8_UINT))
552 /* This call just downloads data, the caller is responsible for binding the
553 * correct texture. */
554 /* Context activation is done by the caller. */
555 static void surface_download_data(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info)
557 const struct wined3d_format *format = This->resource.format;
559 /* Only support read back of converted P8 surfaces */
560 if (This->Flags & SFLAG_CONVERTED && format->id != WINED3DFMT_P8_UINT)
562 FIXME("Readback conversion not supported for format %s.\n", debug_d3dformat(format->id));
568 if (format->Flags & WINED3DFMT_FLAG_COMPRESSED)
570 TRACE("(%p) : Calling glGetCompressedTexImageARB level %d, format %#x, type %#x, data %p.\n",
571 This, This->texture_level, format->glFormat, format->glType,
572 This->resource.allocatedMemory);
574 if (This->Flags & SFLAG_PBO)
576 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
577 checkGLcall("glBindBufferARB");
578 GL_EXTCALL(glGetCompressedTexImageARB(This->texture_target, This->texture_level, NULL));
579 checkGLcall("glGetCompressedTexImageARB");
580 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
581 checkGLcall("glBindBufferARB");
585 GL_EXTCALL(glGetCompressedTexImageARB(This->texture_target,
586 This->texture_level, This->resource.allocatedMemory));
587 checkGLcall("glGetCompressedTexImageARB");
593 GLenum gl_format = format->glFormat;
594 GLenum gl_type = format->glType;
598 /* In case of P8 the index is stored in the alpha component if the primary render target uses P8 */
599 if (format->id == WINED3DFMT_P8_UINT && primary_render_target_is_p8(This->resource.device))
601 gl_format = GL_ALPHA;
602 gl_type = GL_UNSIGNED_BYTE;
605 if (This->Flags & SFLAG_NONPOW2) {
606 unsigned char alignment = This->resource.device->surface_alignment;
607 src_pitch = format->byte_count * This->pow2Width;
608 dst_pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);
609 src_pitch = (src_pitch + alignment - 1) & ~(alignment - 1);
610 mem = HeapAlloc(GetProcessHeap(), 0, src_pitch * This->pow2Height);
612 mem = This->resource.allocatedMemory;
615 TRACE("(%p) : Calling glGetTexImage level %d, format %#x, type %#x, data %p\n",
616 This, This->texture_level, gl_format, gl_type, mem);
618 if(This->Flags & SFLAG_PBO) {
619 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
620 checkGLcall("glBindBufferARB");
622 glGetTexImage(This->texture_target, This->texture_level, gl_format, gl_type, NULL);
623 checkGLcall("glGetTexImage");
625 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
626 checkGLcall("glBindBufferARB");
628 glGetTexImage(This->texture_target, This->texture_level, gl_format, gl_type, mem);
629 checkGLcall("glGetTexImage");
633 if (This->Flags & SFLAG_NONPOW2) {
634 const BYTE *src_data;
638 * Some games (e.g. warhammer 40k) don't work properly with the odd pitches, preventing
639 * the surface pitch from being used to box non-power2 textures. Instead we have to use a hack to
640 * repack the texture so that the bpp * width pitch can be used instead of bpp * pow2width.
642 * We're doing this...
644 * instead of boxing the texture :
645 * |<-texture width ->| -->pow2width| /\
646 * |111111111111111111| | |
647 * |222 Texture 222222| boxed empty | texture height
648 * |3333 Data 33333333| | |
649 * |444444444444444444| | \/
650 * ----------------------------------- |
651 * | boxed empty | boxed empty | pow2height
653 * -----------------------------------
656 * we're repacking the data to the expected texture width
658 * |<-texture width ->| -->pow2width| /\
659 * |111111111111111111222222222222222| |
660 * |222333333333333333333444444444444| texture height
664 * | empty | pow2height
666 * -----------------------------------
670 * |<-texture width ->| /\
671 * |111111111111111111|
672 * |222222222222222222|texture height
673 * |333333333333333333|
674 * |444444444444444444| \/
675 * --------------------
677 * this also means that any references to allocatedMemory should work with the data as if were a
678 * standard texture with a non-power2 width instead of texture boxed up to be a power2 texture.
680 * internally the texture is still stored in a boxed format so any references to textureName will
681 * get a boxed texture with width pow2width and not a texture of width currentDesc.Width.
683 * Performance should not be an issue, because applications normally do not lock the surfaces when
684 * rendering. If an app does, the SFLAG_DYNLOCK flag will kick in and the memory copy won't be released,
685 * and doesn't have to be re-read.
688 dst_data = This->resource.allocatedMemory;
689 TRACE("(%p) : Repacking the surface data from pitch %d to pitch %d\n", This, src_pitch, dst_pitch);
690 for (y = 1 ; y < This->currentDesc.Height; y++) {
691 /* skip the first row */
692 src_data += src_pitch;
693 dst_data += dst_pitch;
694 memcpy(dst_data, src_data, dst_pitch);
697 HeapFree(GetProcessHeap(), 0, mem);
701 /* Surface has now been downloaded */
702 This->Flags |= SFLAG_INSYSMEM;
705 /* This call just uploads data, the caller is responsible for binding the
706 * correct texture. */
707 /* Context activation is done by the caller. */
708 static void surface_upload_data(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
709 const struct wined3d_format *format, BOOL srgb, const GLvoid *data)
711 GLsizei width = This->currentDesc.Width;
712 GLsizei height = This->currentDesc.Height;
717 internal = format->glGammaInternal;
719 else if (This->resource.usage & WINED3DUSAGE_RENDERTARGET && surface_is_offscreen(This))
721 internal = format->rtInternal;
725 internal = format->glInternal;
728 TRACE("This %p, internal %#x, width %d, height %d, format %#x, type %#x, data %p.\n",
729 This, internal, width, height, format->glFormat, format->glType, data);
730 TRACE("target %#x, level %u, resource size %u.\n",
731 This->texture_target, This->texture_level, This->resource.size);
733 if (format->heightscale != 1.0f && format->heightscale != 0.0f) height *= format->heightscale;
737 if (This->Flags & SFLAG_PBO)
739 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
740 checkGLcall("glBindBufferARB");
742 TRACE("(%p) pbo: %#x, data: %p.\n", This, This->pbo, data);
746 if (format->Flags & WINED3DFMT_FLAG_COMPRESSED)
748 TRACE("Calling glCompressedTexSubImage2DARB.\n");
750 GL_EXTCALL(glCompressedTexSubImage2DARB(This->texture_target, This->texture_level,
751 0, 0, width, height, internal, This->resource.size, data));
752 checkGLcall("glCompressedTexSubImage2DARB");
756 TRACE("Calling glTexSubImage2D.\n");
758 glTexSubImage2D(This->texture_target, This->texture_level,
759 0, 0, width, height, format->glFormat, format->glType, data);
760 checkGLcall("glTexSubImage2D");
763 if (This->Flags & SFLAG_PBO)
765 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
766 checkGLcall("glBindBufferARB");
771 if (gl_info->quirks & WINED3D_QUIRK_FBO_TEX_UPDATE)
773 IWineD3DDeviceImpl *device = This->resource.device;
776 for (i = 0; i < device->numContexts; ++i)
778 context_surface_update(device->contexts[i], This);
783 /* This call just allocates the texture, the caller is responsible for binding
784 * the correct texture. */
785 /* Context activation is done by the caller. */
786 static void surface_allocate_surface(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
787 const struct wined3d_format *format, BOOL srgb)
789 BOOL enable_client_storage = FALSE;
790 GLsizei width = This->pow2Width;
791 GLsizei height = This->pow2Height;
792 const BYTE *mem = NULL;
797 internal = format->glGammaInternal;
799 else if (This->resource.usage & WINED3DUSAGE_RENDERTARGET && surface_is_offscreen(This))
801 internal = format->rtInternal;
805 internal = format->glInternal;
808 if (format->heightscale != 1.0f && format->heightscale != 0.0f) height *= format->heightscale;
810 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",
811 This, This->texture_target, This->texture_level, debug_d3dformat(format->id),
812 internal, width, height, format->glFormat, format->glType);
816 if (gl_info->supported[APPLE_CLIENT_STORAGE])
818 if (This->Flags & (SFLAG_NONPOW2 | SFLAG_DIBSECTION | SFLAG_CONVERTED)
819 || !This->resource.allocatedMemory)
821 /* In some cases we want to disable client storage.
822 * SFLAG_NONPOW2 has a bigger opengl texture than the client memory, and different pitches
823 * SFLAG_DIBSECTION: Dibsections may have read / write protections on the memory. Avoid issues...
824 * SFLAG_CONVERTED: The conversion destination memory is freed after loading the surface
825 * allocatedMemory == NULL: Not defined in the extension. Seems to disable client storage effectively
827 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
828 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
829 This->Flags &= ~SFLAG_CLIENT;
830 enable_client_storage = TRUE;
832 This->Flags |= SFLAG_CLIENT;
834 /* Point opengl to our allocated texture memory. Do not use resource.allocatedMemory here because
835 * it might point into a pbo. Instead use heapMemory, but get the alignment right.
837 mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
841 if (format->Flags & WINED3DFMT_FLAG_COMPRESSED && mem)
843 GL_EXTCALL(glCompressedTexImage2DARB(This->texture_target, This->texture_level,
844 internal, width, height, 0, This->resource.size, mem));
845 checkGLcall("glCompressedTexImage2DARB");
849 glTexImage2D(This->texture_target, This->texture_level,
850 internal, width, height, 0, format->glFormat, format->glType, mem);
851 checkGLcall("glTexImage2D");
854 if(enable_client_storage) {
855 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
856 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
861 /* In D3D the depth stencil dimensions have to be greater than or equal to the
862 * render target dimensions. With FBOs, the dimensions have to be an exact match. */
863 /* TODO: We should synchronize the renderbuffer's content with the texture's content. */
864 /* GL locking is done by the caller */
865 void surface_set_compatible_renderbuffer(IWineD3DSurfaceImpl *surface, unsigned int width, unsigned int height)
867 const struct wined3d_gl_info *gl_info = &surface->resource.device->adapter->gl_info;
868 renderbuffer_entry_t *entry;
869 GLuint renderbuffer = 0;
870 unsigned int src_width, src_height;
872 src_width = surface->pow2Width;
873 src_height = surface->pow2Height;
875 /* A depth stencil smaller than the render target is not valid */
876 if (width > src_width || height > src_height) return;
878 /* Remove any renderbuffer set if the sizes match */
879 if (gl_info->supported[ARB_FRAMEBUFFER_OBJECT]
880 || (width == src_width && height == src_height))
882 surface->current_renderbuffer = NULL;
886 /* Look if we've already got a renderbuffer of the correct dimensions */
887 LIST_FOR_EACH_ENTRY(entry, &surface->renderbuffers, renderbuffer_entry_t, entry)
889 if (entry->width == width && entry->height == height)
891 renderbuffer = entry->id;
892 surface->current_renderbuffer = entry;
899 gl_info->fbo_ops.glGenRenderbuffers(1, &renderbuffer);
900 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
901 gl_info->fbo_ops.glRenderbufferStorage(GL_RENDERBUFFER,
902 surface->resource.format->glInternal, width, height);
904 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(renderbuffer_entry_t));
905 entry->width = width;
906 entry->height = height;
907 entry->id = renderbuffer;
908 list_add_head(&surface->renderbuffers, &entry->entry);
910 surface->current_renderbuffer = entry;
913 checkGLcall("set_compatible_renderbuffer");
916 GLenum surface_get_gl_buffer(IWineD3DSurfaceImpl *surface)
918 IWineD3DSwapChainImpl *swapchain = surface->container.u.swapchain;
920 TRACE("surface %p.\n", surface);
922 if (surface->container.type != WINED3D_CONTAINER_SWAPCHAIN)
924 ERR("Surface %p is not on a swapchain.\n", surface);
928 if (swapchain->back_buffers && swapchain->back_buffers[0] == surface)
930 if (swapchain->render_to_fbo)
932 TRACE("Returning GL_COLOR_ATTACHMENT0\n");
933 return GL_COLOR_ATTACHMENT0;
935 TRACE("Returning GL_BACK\n");
938 else if (surface == swapchain->front_buffer)
940 TRACE("Returning GL_FRONT\n");
944 FIXME("Higher back buffer, returning GL_BACK\n");
948 /* Slightly inefficient way to handle multiple dirty rects but it works :) */
949 void surface_add_dirty_rect(IWineD3DSurfaceImpl *surface, const RECT *dirty_rect)
951 TRACE("surface %p, dirty_rect %s.\n", surface, wine_dbgstr_rect(dirty_rect));
953 if (!(surface->Flags & SFLAG_INSYSMEM) && (surface->Flags & SFLAG_INTEXTURE))
954 /* No partial locking for textures yet. */
955 surface_load_location(surface, SFLAG_INSYSMEM, NULL);
957 surface_modify_location(surface, SFLAG_INSYSMEM, TRUE);
960 surface->dirtyRect.left = min(surface->dirtyRect.left, dirty_rect->left);
961 surface->dirtyRect.top = min(surface->dirtyRect.top, dirty_rect->top);
962 surface->dirtyRect.right = max(surface->dirtyRect.right, dirty_rect->right);
963 surface->dirtyRect.bottom = max(surface->dirtyRect.bottom, dirty_rect->bottom);
967 surface->dirtyRect.left = 0;
968 surface->dirtyRect.top = 0;
969 surface->dirtyRect.right = surface->currentDesc.Width;
970 surface->dirtyRect.bottom = surface->currentDesc.Height;
973 /* if the container is a basetexture then mark it dirty. */
974 if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
976 TRACE("Passing to container.\n");
977 IWineD3DBaseTexture_SetDirty((IWineD3DBaseTexture *)surface->container.u.texture, TRUE);
981 static BOOL surface_convert_color_to_float(IWineD3DSurfaceImpl *surface, DWORD color, WINED3DCOLORVALUE *float_color)
983 const struct wined3d_format *format = surface->resource.format;
984 IWineD3DDeviceImpl *device = surface->resource.device;
988 case WINED3DFMT_P8_UINT:
989 if (surface->palette)
991 float_color->r = surface->palette->palents[color].peRed / 255.0f;
992 float_color->g = surface->palette->palents[color].peGreen / 255.0f;
993 float_color->b = surface->palette->palents[color].peBlue / 255.0f;
997 float_color->r = 0.0f;
998 float_color->g = 0.0f;
999 float_color->b = 0.0f;
1001 float_color->a = primary_render_target_is_p8(device) ? color / 255.0f : 1.0f;
1004 case WINED3DFMT_B5G6R5_UNORM:
1005 float_color->r = ((color >> 11) & 0x1f) / 31.0f;
1006 float_color->g = ((color >> 5) & 0x3f) / 63.0f;
1007 float_color->b = (color & 0x1f) / 31.0f;
1008 float_color->a = 1.0f;
1011 case WINED3DFMT_B8G8R8_UNORM:
1012 case WINED3DFMT_B8G8R8X8_UNORM:
1013 float_color->r = D3DCOLOR_R(color);
1014 float_color->g = D3DCOLOR_G(color);
1015 float_color->b = D3DCOLOR_B(color);
1016 float_color->a = 1.0f;
1019 case WINED3DFMT_B8G8R8A8_UNORM:
1020 float_color->r = D3DCOLOR_R(color);
1021 float_color->g = D3DCOLOR_G(color);
1022 float_color->b = D3DCOLOR_B(color);
1023 float_color->a = D3DCOLOR_A(color);
1027 ERR("Unhandled conversion from %s to floating point.\n", debug_d3dformat(format->id));
1034 /* Do not call while under the GL lock. */
1035 static ULONG WINAPI IWineD3DSurfaceImpl_Release(IWineD3DSurface *iface)
1037 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1038 ULONG ref = InterlockedDecrement(&This->resource.ref);
1039 TRACE("(%p) : Releasing from %d\n", This, ref + 1);
1043 surface_cleanup(This);
1044 This->resource.parent_ops->wined3d_object_destroyed(This->resource.parent);
1046 TRACE("(%p) Released.\n", This);
1047 HeapFree(GetProcessHeap(), 0, This);
1053 /* ****************************************************
1054 IWineD3DSurface IWineD3DResource parts follow
1055 **************************************************** */
1057 /* Do not call while under the GL lock. */
1058 void surface_internal_preload(IWineD3DSurfaceImpl *surface, enum WINED3DSRGB srgb)
1060 IWineD3DDeviceImpl *device = surface->resource.device;
1062 TRACE("iface %p, srgb %#x.\n", surface, srgb);
1064 if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
1066 IWineD3DBaseTextureImpl *texture = surface->container.u.texture;
1068 TRACE("Passing to container.\n");
1069 texture->baseTexture.internal_preload((IWineD3DBaseTexture *)texture, srgb);
1073 struct wined3d_context *context = NULL;
1075 TRACE("(%p) : About to load surface\n", surface);
1077 if (!device->isInDraw) context = context_acquire(device, NULL);
1079 if (surface->resource.format->id == WINED3DFMT_P8_UINT
1080 || surface->resource.format->id == WINED3DFMT_P8_UINT_A8_UNORM)
1082 if (palette9_changed(surface))
1084 TRACE("Reloading surface because the d3d8/9 palette was changed\n");
1085 /* TODO: This is not necessarily needed with hw palettized texture support */
1086 surface_load_location(surface, SFLAG_INSYSMEM, NULL);
1087 /* Make sure the texture is reloaded because of the palette change, this kills performance though :( */
1088 surface_modify_location(surface, SFLAG_INTEXTURE, FALSE);
1092 IWineD3DSurface_LoadTexture((IWineD3DSurface *)surface, srgb == SRGB_SRGB ? TRUE : FALSE);
1094 if (surface->resource.pool == WINED3DPOOL_DEFAULT)
1096 /* Tell opengl to try and keep this texture in video ram (well mostly) */
1100 glPrioritizeTextures(1, &surface->texture_name, &tmp);
1104 if (context) context_release(context);
1108 static void WINAPI IWineD3DSurfaceImpl_PreLoad(IWineD3DSurface *iface)
1110 surface_internal_preload((IWineD3DSurfaceImpl *)iface, SRGB_ANY);
1113 /* Context activation is done by the caller. */
1114 static void surface_remove_pbo(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info)
1116 This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
1117 This->resource.allocatedMemory =
1118 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1121 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1122 checkGLcall("glBindBufferARB(GL_PIXEL_UNPACK_BUFFER, This->pbo)");
1123 GL_EXTCALL(glGetBufferSubDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0, This->resource.size, This->resource.allocatedMemory));
1124 checkGLcall("glGetBufferSubDataARB");
1125 GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
1126 checkGLcall("glDeleteBuffersARB");
1130 This->Flags &= ~SFLAG_PBO;
1133 BOOL surface_init_sysmem(IWineD3DSurfaceImpl *surface)
1135 if (!surface->resource.allocatedMemory)
1137 surface->resource.heapMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1138 surface->resource.size + RESOURCE_ALIGNMENT);
1139 if (!surface->resource.heapMemory)
1141 ERR("Out of memory\n");
1144 surface->resource.allocatedMemory =
1145 (BYTE *)(((ULONG_PTR)surface->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1149 memset(surface->resource.allocatedMemory, 0, surface->resource.size);
1152 surface_modify_location(surface, SFLAG_INSYSMEM, TRUE);
1157 /* Do not call while under the GL lock. */
1158 static void WINAPI IWineD3DSurfaceImpl_UnLoad(IWineD3DSurface *iface)
1160 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
1161 IWineD3DDeviceImpl *device = This->resource.device;
1162 const struct wined3d_gl_info *gl_info;
1163 renderbuffer_entry_t *entry, *entry2;
1164 struct wined3d_context *context;
1166 TRACE("(%p)\n", iface);
1168 if(This->resource.pool == WINED3DPOOL_DEFAULT) {
1169 /* Default pool resources are supposed to be destroyed before Reset is called.
1170 * Implicit resources stay however. So this means we have an implicit render target
1171 * or depth stencil. The content may be destroyed, but we still have to tear down
1172 * opengl resources, so we cannot leave early.
1174 * Put the surfaces into sysmem, and reset the content. The D3D content is undefined,
1175 * but we can't set the sysmem INDRAWABLE because when we're rendering the swapchain
1176 * or the depth stencil into an FBO the texture or render buffer will be removed
1177 * and all flags get lost
1179 surface_init_sysmem(This);
1183 /* Load the surface into system memory */
1184 surface_load_location(This, SFLAG_INSYSMEM, NULL);
1185 surface_modify_location(This, SFLAG_INDRAWABLE, FALSE);
1187 surface_modify_location(This, SFLAG_INTEXTURE, FALSE);
1188 surface_modify_location(This, SFLAG_INSRGBTEX, FALSE);
1189 This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
1191 context = context_acquire(device, NULL);
1192 gl_info = context->gl_info;
1194 /* Destroy PBOs, but load them into real sysmem before */
1195 if (This->Flags & SFLAG_PBO)
1196 surface_remove_pbo(This, gl_info);
1198 /* Destroy fbo render buffers. This is needed for implicit render targets, for
1199 * all application-created targets the application has to release the surface
1200 * before calling _Reset
1202 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
1204 gl_info->fbo_ops.glDeleteRenderbuffers(1, &entry->id);
1206 list_remove(&entry->entry);
1207 HeapFree(GetProcessHeap(), 0, entry);
1209 list_init(&This->renderbuffers);
1210 This->current_renderbuffer = NULL;
1212 /* If we're in a texture, the texture name belongs to the texture.
1213 * Otherwise, destroy it. */
1214 if (This->container.type != WINED3D_CONTAINER_TEXTURE)
1217 glDeleteTextures(1, &This->texture_name);
1218 This->texture_name = 0;
1219 glDeleteTextures(1, &This->texture_name_srgb);
1220 This->texture_name_srgb = 0;
1224 context_release(context);
1226 resource_unload((IWineD3DResourceImpl *)This);
1229 /* ******************************************************
1230 IWineD3DSurface IWineD3DSurface parts follow
1231 ****************************************************** */
1233 /* Read the framebuffer back into the surface */
1234 static void read_from_framebuffer(IWineD3DSurfaceImpl *This, const RECT *rect, void *dest, UINT pitch)
1236 IWineD3DDeviceImpl *device = This->resource.device;
1237 const struct wined3d_gl_info *gl_info;
1238 struct wined3d_context *context;
1242 BYTE *row, *top, *bottom;
1246 BOOL srcIsUpsideDown;
1251 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1252 static BOOL warned = FALSE;
1254 ERR("The application tries to lock the render target, but render target locking is disabled\n");
1260 context = context_acquire(device, This);
1261 context_apply_blit_state(context, device);
1262 gl_info = context->gl_info;
1266 /* Select the correct read buffer, and give some debug output.
1267 * There is no need to keep track of the current read buffer or reset it, every part of the code
1268 * that reads sets the read buffer as desired.
1270 if (surface_is_offscreen(This))
1272 /* Mapping the primary render target which is not on a swapchain.
1273 * Read from the back buffer. */
1274 TRACE("Mapping offscreen render target.\n");
1275 glReadBuffer(device->offscreenBuffer);
1276 srcIsUpsideDown = TRUE;
1280 /* Onscreen surfaces are always part of a swapchain */
1281 GLenum buffer = surface_get_gl_buffer(This);
1282 TRACE("Mapping %#x buffer.\n", buffer);
1283 glReadBuffer(buffer);
1284 checkGLcall("glReadBuffer");
1285 srcIsUpsideDown = FALSE;
1288 /* TODO: Get rid of the extra rectangle comparison and construction of a full surface rectangle */
1290 local_rect.left = 0;
1292 local_rect.right = This->currentDesc.Width;
1293 local_rect.bottom = This->currentDesc.Height;
1297 /* TODO: Get rid of the extra GetPitch call, LockRect does that too. Cache the pitch */
1299 switch (This->resource.format->id)
1301 case WINED3DFMT_P8_UINT:
1303 if (primary_render_target_is_p8(device))
1305 /* In case of P8 render targets the index is stored in the alpha component */
1307 type = GL_UNSIGNED_BYTE;
1309 bpp = This->resource.format->byte_count;
1311 /* GL can't return palettized data, so read ARGB pixels into a
1312 * separate block of memory and convert them into palettized format
1313 * in software. Slow, but if the app means to use palettized render
1314 * targets and locks it...
1316 * Use GL_RGB, GL_UNSIGNED_BYTE to read the surface for performance reasons
1317 * Don't use GL_BGR as in the WINED3DFMT_R8G8B8 case, instead watch out
1318 * for the color channels when palettizing the colors.
1321 type = GL_UNSIGNED_BYTE;
1323 mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * 3);
1325 ERR("Out of memory\n");
1329 bpp = This->resource.format->byte_count * 3;
1336 fmt = This->resource.format->glFormat;
1337 type = This->resource.format->glType;
1338 bpp = This->resource.format->byte_count;
1341 if(This->Flags & SFLAG_PBO) {
1342 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
1343 checkGLcall("glBindBufferARB");
1346 ERR("mem not null for pbo -- unexpected\n");
1351 /* Save old pixel store pack state */
1352 glGetIntegerv(GL_PACK_ROW_LENGTH, &rowLen);
1353 checkGLcall("glGetIntegerv");
1354 glGetIntegerv(GL_PACK_SKIP_PIXELS, &skipPix);
1355 checkGLcall("glGetIntegerv");
1356 glGetIntegerv(GL_PACK_SKIP_ROWS, &skipRow);
1357 checkGLcall("glGetIntegerv");
1359 /* Setup pixel store pack state -- to glReadPixels into the correct place */
1360 glPixelStorei(GL_PACK_ROW_LENGTH, This->currentDesc.Width);
1361 checkGLcall("glPixelStorei");
1362 glPixelStorei(GL_PACK_SKIP_PIXELS, local_rect.left);
1363 checkGLcall("glPixelStorei");
1364 glPixelStorei(GL_PACK_SKIP_ROWS, local_rect.top);
1365 checkGLcall("glPixelStorei");
1367 glReadPixels(local_rect.left, (!srcIsUpsideDown) ? (This->currentDesc.Height - local_rect.bottom) : local_rect.top ,
1368 local_rect.right - local_rect.left,
1369 local_rect.bottom - local_rect.top,
1371 checkGLcall("glReadPixels");
1373 /* Reset previous pixel store pack state */
1374 glPixelStorei(GL_PACK_ROW_LENGTH, rowLen);
1375 checkGLcall("glPixelStorei");
1376 glPixelStorei(GL_PACK_SKIP_PIXELS, skipPix);
1377 checkGLcall("glPixelStorei");
1378 glPixelStorei(GL_PACK_SKIP_ROWS, skipRow);
1379 checkGLcall("glPixelStorei");
1381 if(This->Flags & SFLAG_PBO) {
1382 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
1383 checkGLcall("glBindBufferARB");
1385 /* Check if we need to flip the image. If we need to flip use glMapBufferARB
1386 * to get a pointer to it and perform the flipping in software. This is a lot
1387 * faster than calling glReadPixels for each line. In case we want more speed
1388 * we should rerender it flipped in a FBO and read the data back from the FBO. */
1389 if(!srcIsUpsideDown) {
1390 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1391 checkGLcall("glBindBufferARB");
1393 mem = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1394 checkGLcall("glMapBufferARB");
1398 /* TODO: Merge this with the palettization loop below for P8 targets */
1399 if(!srcIsUpsideDown) {
1401 /* glReadPixels returns the image upside down, and there is no way to prevent this.
1402 Flip the lines in software */
1403 len = (local_rect.right - local_rect.left) * bpp;
1404 off = local_rect.left * bpp;
1406 row = HeapAlloc(GetProcessHeap(), 0, len);
1408 ERR("Out of memory\n");
1409 if (This->resource.format->id == WINED3DFMT_P8_UINT) HeapFree(GetProcessHeap(), 0, mem);
1414 top = mem + pitch * local_rect.top;
1415 bottom = mem + pitch * (local_rect.bottom - 1);
1416 for(i = 0; i < (local_rect.bottom - local_rect.top) / 2; i++) {
1417 memcpy(row, top + off, len);
1418 memcpy(top + off, bottom + off, len);
1419 memcpy(bottom + off, row, len);
1423 HeapFree(GetProcessHeap(), 0, row);
1425 /* Unmap the temp PBO buffer */
1426 if(This->Flags & SFLAG_PBO) {
1427 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1428 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1433 context_release(context);
1435 /* For P8 textures we need to perform an inverse palette lookup. This is done by searching for a palette
1436 * index which matches the RGB value. Note this isn't guaranteed to work when there are multiple entries for
1437 * the same color but we have no choice.
1438 * In case of P8 render targets, the index is stored in the alpha component so no conversion is needed.
1440 if (This->resource.format->id == WINED3DFMT_P8_UINT && !primary_render_target_is_p8(device))
1442 const PALETTEENTRY *pal = NULL;
1443 DWORD width = pitch / 3;
1447 pal = This->palette->palents;
1449 ERR("Palette is missing, cannot perform inverse palette lookup\n");
1450 HeapFree(GetProcessHeap(), 0, mem);
1454 for(y = local_rect.top; y < local_rect.bottom; y++) {
1455 for(x = local_rect.left; x < local_rect.right; x++) {
1456 /* start lines pixels */
1457 const BYTE *blue = mem + y * pitch + x * (sizeof(BYTE) * 3);
1458 const BYTE *green = blue + 1;
1459 const BYTE *red = green + 1;
1461 for(c = 0; c < 256; c++) {
1462 if(*red == pal[c].peRed &&
1463 *green == pal[c].peGreen &&
1464 *blue == pal[c].peBlue)
1466 *((BYTE *) dest + y * width + x) = c;
1472 HeapFree(GetProcessHeap(), 0, mem);
1476 /* Read the framebuffer contents into a texture */
1477 static void read_from_framebuffer_texture(IWineD3DSurfaceImpl *This, BOOL srgb)
1479 IWineD3DDeviceImpl *device = This->resource.device;
1480 const struct wined3d_gl_info *gl_info;
1481 struct wined3d_context *context;
1483 if (!surface_is_offscreen(This))
1485 /* We would need to flip onscreen surfaces, but there's no efficient
1486 * way to do that here. It makes more sense for the caller to
1487 * explicitly go through sysmem. */
1488 ERR("Not supported for onscreen targets.\n");
1492 /* Activate the surface to read from. In some situations it isn't the currently active target(e.g. backbuffer
1493 * locking during offscreen rendering). RESOURCELOAD is ok because glCopyTexSubImage2D isn't affected by any
1494 * states in the stateblock, and no driver was found yet that had bugs in that regard.
1496 context = context_acquire(device, This);
1497 gl_info = context->gl_info;
1499 surface_prepare_texture(This, gl_info, srgb);
1500 surface_bind_and_dirtify(This, srgb);
1502 TRACE("Reading back offscreen render target %p.\n", This);
1506 glReadBuffer(device->offscreenBuffer);
1507 checkGLcall("glReadBuffer");
1509 glCopyTexSubImage2D(This->texture_target, This->texture_level,
1510 0, 0, 0, 0, This->currentDesc.Width, This->currentDesc.Height);
1511 checkGLcall("glCopyTexSubImage2D");
1515 context_release(context);
1518 /* Context activation is done by the caller. */
1519 static void surface_prepare_texture_internal(IWineD3DSurfaceImpl *surface,
1520 const struct wined3d_gl_info *gl_info, BOOL srgb)
1522 DWORD alloc_flag = srgb ? SFLAG_SRGBALLOCATED : SFLAG_ALLOCATED;
1523 CONVERT_TYPES convert;
1524 struct wined3d_format format;
1526 if (surface->Flags & alloc_flag) return;
1528 d3dfmt_get_conv(surface, TRUE, TRUE, &format, &convert);
1529 if (convert != NO_CONVERSION || format.convert) surface->Flags |= SFLAG_CONVERTED;
1530 else surface->Flags &= ~SFLAG_CONVERTED;
1532 surface_bind_and_dirtify(surface, srgb);
1533 surface_allocate_surface(surface, gl_info, &format, srgb);
1534 surface->Flags |= alloc_flag;
1537 /* Context activation is done by the caller. */
1538 void surface_prepare_texture(IWineD3DSurfaceImpl *surface, const struct wined3d_gl_info *gl_info, BOOL srgb)
1540 if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
1542 IWineD3DBaseTextureImpl *texture = surface->container.u.texture;
1543 UINT sub_count = texture->baseTexture.level_count * texture->baseTexture.layer_count;
1546 TRACE("surface %p is a subresource of texture %p.\n", surface, texture);
1548 for (i = 0; i < sub_count; ++i)
1550 IWineD3DSurfaceImpl *s = (IWineD3DSurfaceImpl *)texture->baseTexture.sub_resources[i];
1551 surface_prepare_texture_internal(s, gl_info, srgb);
1557 surface_prepare_texture_internal(surface, gl_info, srgb);
1560 static void surface_prepare_system_memory(IWineD3DSurfaceImpl *This)
1562 IWineD3DDeviceImpl *device = This->resource.device;
1563 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1565 /* Performance optimization: Count how often a surface is locked, if it is locked regularly do not throw away the system memory copy.
1566 * This avoids the need to download the surface from opengl all the time. The surface is still downloaded if the opengl texture is
1569 if(!(This->Flags & SFLAG_DYNLOCK)) {
1571 /* MAXLOCKCOUNT is defined in wined3d_private.h */
1572 if(This->lockCount > MAXLOCKCOUNT) {
1573 TRACE("Surface is locked regularly, not freeing the system memory copy any more\n");
1574 This->Flags |= SFLAG_DYNLOCK;
1578 /* Create a PBO for dynamically locked surfaces but don't do it for converted or non-pow2 surfaces.
1579 * Also don't create a PBO for systemmem surfaces.
1581 if (gl_info->supported[ARB_PIXEL_BUFFER_OBJECT] && (This->Flags & SFLAG_DYNLOCK)
1582 && !(This->Flags & (SFLAG_PBO | SFLAG_CONVERTED | SFLAG_NONPOW2))
1583 && (This->resource.pool != WINED3DPOOL_SYSTEMMEM))
1586 struct wined3d_context *context;
1588 context = context_acquire(device, NULL);
1591 GL_EXTCALL(glGenBuffersARB(1, &This->pbo));
1592 error = glGetError();
1593 if (!This->pbo || error != GL_NO_ERROR)
1594 ERR("Failed to bind the PBO with error %s (%#x)\n", debug_glerror(error), error);
1596 TRACE("Attaching pbo=%#x to (%p)\n", This->pbo, This);
1598 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1599 checkGLcall("glBindBufferARB");
1601 GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->resource.size + 4, This->resource.allocatedMemory, GL_STREAM_DRAW_ARB));
1602 checkGLcall("glBufferDataARB");
1604 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1605 checkGLcall("glBindBufferARB");
1607 /* We don't need the system memory anymore and we can't even use it for PBOs */
1608 if(!(This->Flags & SFLAG_CLIENT)) {
1609 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
1610 This->resource.heapMemory = NULL;
1612 This->resource.allocatedMemory = NULL;
1613 This->Flags |= SFLAG_PBO;
1615 context_release(context);
1617 else if (!(This->resource.allocatedMemory || This->Flags & SFLAG_PBO))
1619 /* Whatever surface we have, make sure that there is memory allocated for the downloaded copy,
1622 if(!This->resource.heapMemory) {
1623 This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
1625 This->resource.allocatedMemory =
1626 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1627 if(This->Flags & SFLAG_INSYSMEM) {
1628 ERR("Surface without memory or pbo has SFLAG_INSYSMEM set!\n");
1633 static HRESULT WINAPI IWineD3DSurfaceImpl_Map(IWineD3DSurface *iface,
1634 WINED3DLOCKED_RECT *pLockedRect, const RECT *pRect, DWORD Flags)
1636 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1637 IWineD3DDeviceImpl *device = This->resource.device;
1638 const RECT *pass_rect = pRect;
1640 TRACE("iface %p, locked_rect %p, rect %s, flags %#x.\n",
1641 iface, pLockedRect, wine_dbgstr_rect(pRect), Flags);
1643 /* This is also done in the base class, but we have to verify this before loading any data from
1644 * gl into the sysmem copy. The PBO may be mapped, a different rectangle locked, the discard flag
1645 * may interfere, and all other bad things may happen
1647 if (This->Flags & SFLAG_LOCKED) {
1648 WARN("Surface is already locked, returning D3DERR_INVALIDCALL\n");
1649 return WINED3DERR_INVALIDCALL;
1651 This->Flags |= SFLAG_LOCKED;
1653 if (!(This->Flags & SFLAG_LOCKABLE))
1655 TRACE("Warning: trying to lock unlockable surf@%p\n", This);
1658 if (Flags & WINED3DLOCK_DISCARD) {
1659 /* Set SFLAG_INSYSMEM, so we'll never try to download the data from the texture. */
1660 TRACE("WINED3DLOCK_DISCARD flag passed, marking local copy as up to date\n");
1661 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1662 This->Flags |= SFLAG_INSYSMEM;
1666 if (This->Flags & SFLAG_INSYSMEM) {
1667 TRACE("Local copy is up to date, not downloading data\n");
1668 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1672 /* surface_load_location() does not check if the rectangle specifies
1673 * the full surface. Most callers don't need that, so do it here. */
1674 if (pRect && !pRect->top && !pRect->left
1675 && pRect->right == This->currentDesc.Width
1676 && pRect->bottom == This->currentDesc.Height)
1681 if (!(wined3d_settings.rendertargetlock_mode == RTL_DISABLE
1682 && ((This->container.type == WINED3D_CONTAINER_SWAPCHAIN) || This == device->render_targets[0])))
1684 surface_load_location(This, SFLAG_INSYSMEM, pass_rect);
1688 if (This->Flags & SFLAG_PBO)
1690 const struct wined3d_gl_info *gl_info;
1691 struct wined3d_context *context;
1693 context = context_acquire(device, NULL);
1694 gl_info = context->gl_info;
1697 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1698 checkGLcall("glBindBufferARB");
1700 /* This shouldn't happen but could occur if some other function didn't handle the PBO properly */
1701 if(This->resource.allocatedMemory) {
1702 ERR("The surface already has PBO memory allocated!\n");
1705 This->resource.allocatedMemory = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1706 checkGLcall("glMapBufferARB");
1708 /* Make sure the pbo isn't set anymore in order not to break non-pbo calls */
1709 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1710 checkGLcall("glBindBufferARB");
1713 context_release(context);
1716 if (Flags & (WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY)) {
1721 surface_add_dirty_rect(This, pRect);
1723 if (This->container.type == WINED3D_CONTAINER_TEXTURE)
1725 TRACE("Making container dirty.\n");
1726 IWineD3DBaseTexture_SetDirty((IWineD3DBaseTexture *)This->container.u.texture, TRUE);
1730 TRACE("Surface is standalone, no need to dirty the container\n");
1734 return IWineD3DBaseSurfaceImpl_Map(iface, pLockedRect, pRect, Flags);
1737 static void flush_to_framebuffer_drawpixels(IWineD3DSurfaceImpl *This, GLenum fmt, GLenum type, UINT bpp, const BYTE *mem) {
1739 GLint prev_rasterpos[4];
1740 GLint skipBytes = 0;
1741 UINT pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This); /* target is argb, 4 byte */
1742 IWineD3DDeviceImpl *device = This->resource.device;
1743 const struct wined3d_gl_info *gl_info;
1744 struct wined3d_context *context;
1746 /* Activate the correct context for the render target */
1747 context = context_acquire(device, This);
1748 context_apply_blit_state(context, device);
1749 gl_info = context->gl_info;
1753 if (!surface_is_offscreen(This))
1755 GLenum buffer = surface_get_gl_buffer(This);
1756 TRACE("Unlocking %#x buffer.\n", buffer);
1757 context_set_draw_buffer(context, buffer);
1761 /* Primary offscreen render target */
1762 TRACE("Offscreen render target.\n");
1763 context_set_draw_buffer(context, device->offscreenBuffer);
1766 glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
1767 checkGLcall("glGetIntegerv");
1768 glGetIntegerv(GL_CURRENT_RASTER_POSITION, &prev_rasterpos[0]);
1769 checkGLcall("glGetIntegerv");
1770 glPixelZoom(1.0f, -1.0f);
1771 checkGLcall("glPixelZoom");
1773 /* If not fullscreen, we need to skip a number of bytes to find the next row of data */
1774 glGetIntegerv(GL_UNPACK_ROW_LENGTH, &skipBytes);
1775 glPixelStorei(GL_UNPACK_ROW_LENGTH, This->currentDesc.Width);
1777 glRasterPos3i(This->lockedRect.left, This->lockedRect.top, 1);
1778 checkGLcall("glRasterPos3i");
1780 /* Some drivers(radeon dri, others?) don't like exceptions during
1781 * glDrawPixels. If the surface is a DIB section, it might be in GDIMode
1782 * after ReleaseDC. Reading it will cause an exception, which x11drv will
1783 * catch to put the dib section in InSync mode, which leads to a crash
1784 * and a blocked x server on my radeon card.
1786 * The following lines read the dib section so it is put in InSync mode
1787 * before glDrawPixels is called and the crash is prevented. There won't
1788 * be any interfering gdi accesses, because UnlockRect is called from
1789 * ReleaseDC, and the app won't use the dc any more afterwards.
1791 if((This->Flags & SFLAG_DIBSECTION) && !(This->Flags & SFLAG_PBO)) {
1793 read = This->resource.allocatedMemory[0];
1796 if(This->Flags & SFLAG_PBO) {
1797 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1798 checkGLcall("glBindBufferARB");
1801 /* When the surface is locked we only have to refresh the locked part else we need to update the whole image */
1802 if(This->Flags & SFLAG_LOCKED) {
1803 glDrawPixels(This->lockedRect.right - This->lockedRect.left,
1804 (This->lockedRect.bottom - This->lockedRect.top)-1,
1806 mem + bpp * This->lockedRect.left + pitch * This->lockedRect.top);
1807 checkGLcall("glDrawPixels");
1809 glDrawPixels(This->currentDesc.Width,
1810 This->currentDesc.Height,
1812 checkGLcall("glDrawPixels");
1815 if(This->Flags & SFLAG_PBO) {
1816 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1817 checkGLcall("glBindBufferARB");
1820 glPixelZoom(1.0f, 1.0f);
1821 checkGLcall("glPixelZoom");
1823 glRasterPos3iv(&prev_rasterpos[0]);
1824 checkGLcall("glRasterPos3iv");
1826 /* Reset to previous pack row length */
1827 glPixelStorei(GL_UNPACK_ROW_LENGTH, skipBytes);
1828 checkGLcall("glPixelStorei(GL_UNPACK_ROW_LENGTH)");
1831 context_release(context);
1834 static HRESULT WINAPI IWineD3DSurfaceImpl_Unmap(IWineD3DSurface *iface)
1836 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1837 IWineD3DDeviceImpl *device = This->resource.device;
1840 if (!(This->Flags & SFLAG_LOCKED)) {
1841 WARN("trying to Unlock an unlocked surf@%p\n", This);
1842 return WINEDDERR_NOTLOCKED;
1845 if (This->Flags & SFLAG_PBO)
1847 const struct wined3d_gl_info *gl_info;
1848 struct wined3d_context *context;
1850 TRACE("Freeing PBO memory\n");
1852 context = context_acquire(device, NULL);
1853 gl_info = context->gl_info;
1856 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1857 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1858 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1859 checkGLcall("glUnmapBufferARB");
1861 context_release(context);
1863 This->resource.allocatedMemory = NULL;
1866 TRACE("(%p) : dirtyfied(%d)\n", This, This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
1868 if (This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE)) {
1869 TRACE("(%p) : Not Dirtified so nothing to do, return now\n", This);
1873 if (This->container.type == WINED3D_CONTAINER_SWAPCHAIN
1874 || (device->render_targets && This == device->render_targets[0]))
1876 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1877 static BOOL warned = FALSE;
1879 ERR("The application tries to write to the render target, but render target locking is disabled\n");
1885 if (!This->dirtyRect.left && !This->dirtyRect.top
1886 && This->dirtyRect.right == This->currentDesc.Width
1887 && This->dirtyRect.bottom == This->currentDesc.Height)
1891 /* TODO: Proper partial rectangle tracking */
1892 fullsurface = FALSE;
1893 This->Flags |= SFLAG_INSYSMEM;
1896 switch(wined3d_settings.rendertargetlock_mode) {
1898 surface_load_location(This, SFLAG_INTEXTURE, NULL /* partial texture loading not supported yet */);
1902 surface_load_location(This, SFLAG_INDRAWABLE, fullsurface ? NULL : &This->dirtyRect);
1908 /* Partial rectangle tracking is not commonly implemented, it is
1909 * only done for render targets. Overwrite the flags to bring
1910 * them back into a sane state. INSYSMEM was set before to tell
1911 * surface_load_location() where to read the rectangle from.
1912 * Indrawable is set because all modifications from the partial
1913 * sysmem copy are written back to the drawable, thus the surface
1914 * is merged again in the drawable. The sysmem copy is not fully
1915 * up to date because only a subrectangle was read in Map(). */
1916 This->Flags &= ~SFLAG_INSYSMEM;
1917 This->Flags |= SFLAG_INDRAWABLE;
1920 This->dirtyRect.left = This->currentDesc.Width;
1921 This->dirtyRect.top = This->currentDesc.Height;
1922 This->dirtyRect.right = 0;
1923 This->dirtyRect.bottom = 0;
1925 else if (This == device->depth_stencil)
1927 FIXME("Depth Stencil buffer locking is not implemented\n");
1929 /* The rest should be a normal texture */
1930 /* Check if the texture is bound, if yes dirtify the sampler to force a re-upload of the texture
1931 * Can't load the texture here because PreLoad may destroy and recreate the gl texture, so sampler
1932 * states need resetting
1934 if (This->container.type == WINED3D_CONTAINER_TEXTURE)
1936 IWineD3DBaseTextureImpl *texture = This->container.u.texture;
1937 if (texture->baseTexture.bindCount)
1938 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(texture->baseTexture.sampler));
1943 This->Flags &= ~SFLAG_LOCKED;
1944 memset(&This->lockedRect, 0, sizeof(RECT));
1946 /* Overlays have to be redrawn manually after changes with the GL implementation */
1947 if(This->overlay_dest) {
1948 IWineD3DSurface_DrawOverlay(iface);
1953 static void surface_release_client_storage(IWineD3DSurfaceImpl *surface)
1955 struct wined3d_context *context;
1957 context = context_acquire(surface->resource.device, NULL);
1960 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
1961 if (surface->texture_name)
1963 surface_bind_and_dirtify(surface, FALSE);
1964 glTexImage2D(surface->texture_target, surface->texture_level,
1965 GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
1967 if (surface->texture_name_srgb)
1969 surface_bind_and_dirtify(surface, TRUE);
1970 glTexImage2D(surface->texture_target, surface->texture_level,
1971 GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
1973 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1976 context_release(context);
1978 surface_modify_location(surface, SFLAG_INSRGBTEX, FALSE);
1979 surface_modify_location(surface, SFLAG_INTEXTURE, FALSE);
1980 surface_force_reload(surface);
1983 static HRESULT WINAPI IWineD3DSurfaceImpl_GetDC(IWineD3DSurface *iface, HDC *pHDC)
1985 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1986 WINED3DLOCKED_RECT lock;
1990 TRACE("(%p)->(%p)\n",This,pHDC);
1992 if(This->Flags & SFLAG_USERPTR) {
1993 ERR("Not supported on surfaces with an application-provided surfaces\n");
1994 return WINEDDERR_NODC;
1997 /* Give more detailed info for ddraw */
1998 if (This->Flags & SFLAG_DCINUSE)
1999 return WINEDDERR_DCALREADYCREATED;
2001 /* Can't GetDC if the surface is locked */
2002 if (This->Flags & SFLAG_LOCKED)
2003 return WINED3DERR_INVALIDCALL;
2005 memset(&lock, 0, sizeof(lock)); /* To be sure */
2007 /* Create a DIB section if there isn't a hdc yet */
2010 if (This->Flags & SFLAG_CLIENT)
2012 surface_load_location(This, SFLAG_INSYSMEM, NULL);
2013 surface_release_client_storage(This);
2015 hr = IWineD3DBaseSurfaceImpl_CreateDIBSection(iface);
2016 if(FAILED(hr)) return WINED3DERR_INVALIDCALL;
2018 /* Use the dib section from now on if we are not using a PBO */
2019 if(!(This->Flags & SFLAG_PBO))
2020 This->resource.allocatedMemory = This->dib.bitmap_data;
2023 /* Map the surface */
2024 hr = IWineD3DSurface_Map(iface, &lock, NULL, 0);
2026 /* Sync the DIB with the PBO. This can't be done earlier because Map()
2027 * activates the allocatedMemory. */
2028 if (This->Flags & SFLAG_PBO)
2029 memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, This->dib.bitmap_size);
2033 ERR("IWineD3DSurface_Map failed, hr %#x.\n", hr);
2034 /* keep the dib section */
2038 if (This->resource.format->id == WINED3DFMT_P8_UINT
2039 || This->resource.format->id == WINED3DFMT_P8_UINT_A8_UNORM)
2041 /* GetDC on palettized formats is unsupported in D3D9, and the method is missing in
2042 D3D8, so this should only be used for DX <=7 surfaces (with non-device palettes) */
2044 const PALETTEENTRY *pal = NULL;
2047 pal = This->palette->palents;
2049 IWineD3DSurfaceImpl *dds_primary;
2050 IWineD3DSwapChainImpl *swapchain;
2051 swapchain = (IWineD3DSwapChainImpl *)This->resource.device->swapchains[0];
2052 dds_primary = swapchain->front_buffer;
2053 if (dds_primary && dds_primary->palette)
2054 pal = dds_primary->palette->palents;
2058 for (n=0; n<256; n++) {
2059 col[n].rgbRed = pal[n].peRed;
2060 col[n].rgbGreen = pal[n].peGreen;
2061 col[n].rgbBlue = pal[n].peBlue;
2062 col[n].rgbReserved = 0;
2064 SetDIBColorTable(This->hDC, 0, 256, col);
2069 TRACE("returning %p\n",*pHDC);
2070 This->Flags |= SFLAG_DCINUSE;
2075 static HRESULT WINAPI IWineD3DSurfaceImpl_ReleaseDC(IWineD3DSurface *iface, HDC hDC)
2077 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2079 TRACE("(%p)->(%p)\n",This,hDC);
2081 if (!(This->Flags & SFLAG_DCINUSE))
2082 return WINEDDERR_NODC;
2084 if (This->hDC !=hDC) {
2085 WARN("Application tries to release an invalid DC(%p), surface dc is %p\n", hDC, This->hDC);
2086 return WINEDDERR_NODC;
2089 if((This->Flags & SFLAG_PBO) && This->resource.allocatedMemory) {
2090 /* Copy the contents of the DIB over to the PBO */
2091 memcpy(This->resource.allocatedMemory, This->dib.bitmap_data, This->dib.bitmap_size);
2094 /* we locked first, so unlock now */
2095 IWineD3DSurface_Unmap(iface);
2097 This->Flags &= ~SFLAG_DCINUSE;
2102 /* ******************************************************
2103 IWineD3DSurface Internal (No mapping to directx api) parts follow
2104 ****************************************************** */
2106 HRESULT d3dfmt_get_conv(IWineD3DSurfaceImpl *This, BOOL need_alpha_ck,
2107 BOOL use_texturing, struct wined3d_format *format, CONVERT_TYPES *convert)
2109 BOOL colorkey_active = need_alpha_ck && (This->CKeyFlags & WINEDDSD_CKSRCBLT);
2110 IWineD3DDeviceImpl *device = This->resource.device;
2111 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2112 BOOL blit_supported = FALSE;
2114 /* Copy the default values from the surface. Below we might perform fixups */
2115 /* TODO: get rid of color keying desc fixups by using e.g. a table. */
2116 *format = *This->resource.format;
2117 *convert = NO_CONVERSION;
2119 /* Ok, now look if we have to do any conversion */
2120 switch (This->resource.format->id)
2122 case WINED3DFMT_P8_UINT:
2123 /* Below the call to blit_supported is disabled for Wine 1.2
2124 * because the function isn't operating correctly yet. At the
2125 * moment 8-bit blits are handled in software and if certain GL
2126 * extensions are around, surface conversion is performed at
2127 * upload time. The blit_supported call recognizes it as a
2128 * destination fixup. This type of upload 'fixup' and 8-bit to
2129 * 8-bit blits need to be handled by the blit_shader.
2130 * TODO: get rid of this #if 0. */
2132 blit_supported = device->blitter->blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
2133 &rect, This->resource.usage, This->resource.pool, This->resource.format,
2134 &rect, This->resource.usage, This->resource.pool, This->resource.format);
2136 blit_supported = gl_info->supported[EXT_PALETTED_TEXTURE] || gl_info->supported[ARB_FRAGMENT_PROGRAM];
2138 /* Use conversion when the blit_shader backend supports it. It only supports this in case of
2139 * texturing. Further also use conversion in case of color keying.
2140 * Paletted textures can be emulated using shaders but only do that for 2D purposes e.g. situations
2141 * in which the main render target uses p8. Some games like GTA Vice City use P8 for texturing which
2142 * conflicts with this.
2144 if (!((blit_supported && device->render_targets && This == device->render_targets[0]))
2145 || colorkey_active || !use_texturing)
2147 format->glFormat = GL_RGBA;
2148 format->glInternal = GL_RGBA;
2149 format->glType = GL_UNSIGNED_BYTE;
2150 format->conv_byte_count = 4;
2151 if (colorkey_active)
2152 *convert = CONVERT_PALETTED_CK;
2154 *convert = CONVERT_PALETTED;
2158 case WINED3DFMT_B2G3R3_UNORM:
2159 /* **********************
2160 GL_UNSIGNED_BYTE_3_3_2
2161 ********************** */
2162 if (colorkey_active) {
2163 /* This texture format will never be used.. So do not care about color keying
2164 up until the point in time it will be needed :-) */
2165 FIXME(" ColorKeying not supported in the RGB 332 format !\n");
2169 case WINED3DFMT_B5G6R5_UNORM:
2170 if (colorkey_active)
2172 *convert = CONVERT_CK_565;
2173 format->glFormat = GL_RGBA;
2174 format->glInternal = GL_RGB5_A1;
2175 format->glType = GL_UNSIGNED_SHORT_5_5_5_1;
2176 format->conv_byte_count = 2;
2180 case WINED3DFMT_B5G5R5X1_UNORM:
2181 if (colorkey_active)
2183 *convert = CONVERT_CK_5551;
2184 format->glFormat = GL_BGRA;
2185 format->glInternal = GL_RGB5_A1;
2186 format->glType = GL_UNSIGNED_SHORT_1_5_5_5_REV;
2187 format->conv_byte_count = 2;
2191 case WINED3DFMT_B8G8R8_UNORM:
2192 if (colorkey_active)
2194 *convert = CONVERT_CK_RGB24;
2195 format->glFormat = GL_RGBA;
2196 format->glInternal = GL_RGBA8;
2197 format->glType = GL_UNSIGNED_INT_8_8_8_8;
2198 format->conv_byte_count = 4;
2202 case WINED3DFMT_B8G8R8X8_UNORM:
2203 if (colorkey_active)
2205 *convert = CONVERT_RGB32_888;
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;
2220 void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey)
2222 IWineD3DDeviceImpl *device = This->resource.device;
2223 IWineD3DPaletteImpl *pal = This->palette;
2224 BOOL index_in_alpha = FALSE;
2227 /* Old games like StarCraft, C&C, Red Alert and others use P8 render targets.
2228 * Reading back the RGB output each lockrect (each frame as they lock the whole screen)
2229 * is slow. Further RGB->P8 conversion is not possible because palettes can have
2230 * duplicate entries. Store the color key in the unused alpha component to speed the
2231 * download up and to make conversion unneeded. */
2232 index_in_alpha = primary_render_target_is_p8(device);
2236 UINT dxVersion = ((IWineD3DImpl *)device->wined3d)->dxVersion;
2238 /* In DirectDraw the palette is a property of the surface, there are no such things as device palettes. */
2241 ERR("This code should never get entered for DirectDraw!, expect problems\n");
2244 /* Guarantees that memory representation remains correct after sysmem<->texture transfers even if
2245 * there's no palette at this time. */
2246 for (i = 0; i < 256; i++) table[i][3] = i;
2251 /* Direct3D >= 8 palette usage style: P8 textures use device palettes, palette entry format is A8R8G8B8,
2252 * alpha is stored in peFlags and may be used by the app if D3DPTEXTURECAPS_ALPHAPALETTE device
2253 * capability flag is present (wine does advertise this capability) */
2254 for (i = 0; i < 256; ++i)
2256 table[i][0] = device->palettes[device->currentPalette][i].peRed;
2257 table[i][1] = device->palettes[device->currentPalette][i].peGreen;
2258 table[i][2] = device->palettes[device->currentPalette][i].peBlue;
2259 table[i][3] = device->palettes[device->currentPalette][i].peFlags;
2265 TRACE("Using surface palette %p\n", pal);
2266 /* Get the surface's palette */
2267 for (i = 0; i < 256; ++i)
2269 table[i][0] = pal->palents[i].peRed;
2270 table[i][1] = pal->palents[i].peGreen;
2271 table[i][2] = pal->palents[i].peBlue;
2273 /* When index_in_alpha is set the palette index is stored in the
2274 * alpha component. In case of a readback we can then read
2275 * GL_ALPHA. Color keying is handled in BltOverride using a
2276 * GL_ALPHA_TEST using GL_NOT_EQUAL. In case of index_in_alpha the
2277 * color key itself is passed to glAlphaFunc in other cases the
2278 * alpha component of pixels that should be masked away is set to 0. */
2283 else if (colorkey && (i >= This->SrcBltCKey.dwColorSpaceLowValue)
2284 && (i <= This->SrcBltCKey.dwColorSpaceHighValue))
2288 else if(pal->Flags & WINEDDPCAPS_ALPHA)
2290 table[i][3] = pal->palents[i].peFlags;
2300 static HRESULT d3dfmt_convert_surface(const BYTE *src, BYTE *dst, UINT pitch, UINT width,
2301 UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *This)
2305 TRACE("(%p)->(%p),(%d,%d,%d,%d,%p)\n", src, dst, pitch, height, outpitch, convert,This);
2310 memcpy(dst, src, pitch * height);
2313 case CONVERT_PALETTED:
2314 case CONVERT_PALETTED_CK:
2319 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
2321 for (y = 0; y < height; y++)
2323 source = src + pitch * y;
2324 dest = dst + outpitch * y;
2325 /* This is an 1 bpp format, using the width here is fine */
2326 for (x = 0; x < width; x++) {
2327 BYTE color = *source++;
2328 *dest++ = table[color][0];
2329 *dest++ = table[color][1];
2330 *dest++ = table[color][2];
2331 *dest++ = table[color][3];
2337 case CONVERT_CK_565:
2339 /* Converting the 565 format in 5551 packed to emulate color-keying.
2341 Note : in all these conversion, it would be best to average the averaging
2342 pixels to get the color of the pixel that will be color-keyed to
2343 prevent 'color bleeding'. This will be done later on if ever it is
2346 Note2: Nvidia documents say that their driver does not support alpha + color keying
2347 on the same surface and disables color keying in such a case
2353 TRACE("Color keyed 565\n");
2355 for (y = 0; y < height; y++) {
2356 Source = (const WORD *)(src + y * pitch);
2357 Dest = (WORD *) (dst + y * outpitch);
2358 for (x = 0; x < width; x++ ) {
2359 WORD color = *Source++;
2360 *Dest = ((color & 0xFFC0) | ((color & 0x1F) << 1));
2361 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2362 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2371 case CONVERT_CK_5551:
2373 /* Converting X1R5G5B5 format to R5G5B5A1 to emulate color-keying. */
2377 TRACE("Color keyed 5551\n");
2378 for (y = 0; y < height; y++) {
2379 Source = (const WORD *)(src + y * pitch);
2380 Dest = (WORD *) (dst + y * outpitch);
2381 for (x = 0; x < width; x++ ) {
2382 WORD color = *Source++;
2384 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2385 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2389 *Dest &= ~(1 << 15);
2397 case CONVERT_CK_RGB24:
2399 /* Converting R8G8B8 format to R8G8B8A8 with color-keying. */
2401 for (y = 0; y < height; y++)
2403 source = src + pitch * y;
2404 dest = dst + outpitch * y;
2405 for (x = 0; x < width; x++) {
2406 DWORD color = ((DWORD)source[0] << 16) + ((DWORD)source[1] << 8) + (DWORD)source[2] ;
2407 DWORD dstcolor = color << 8;
2408 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2409 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2412 *(DWORD*)dest = dstcolor;
2420 case CONVERT_RGB32_888:
2422 /* Converting X8R8G8B8 format to R8G8B8A8 with color-keying. */
2424 for (y = 0; y < height; y++)
2426 source = src + pitch * y;
2427 dest = dst + outpitch * y;
2428 for (x = 0; x < width; x++) {
2429 DWORD color = 0xffffff & *(const DWORD*)source;
2430 DWORD dstcolor = color << 8;
2431 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2432 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2435 *(DWORD*)dest = dstcolor;
2444 ERR("Unsupported conversion type %#x.\n", convert);
2449 BOOL palette9_changed(IWineD3DSurfaceImpl *This)
2451 IWineD3DDeviceImpl *device = This->resource.device;
2453 if (This->palette || (This->resource.format->id != WINED3DFMT_P8_UINT
2454 && This->resource.format->id != WINED3DFMT_P8_UINT_A8_UNORM))
2456 /* If a ddraw-style palette is attached assume no d3d9 palette change.
2457 * Also the palette isn't interesting if the surface format isn't P8 or A8P8
2464 if (!memcmp(This->palette9, device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256))
2469 This->palette9 = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
2471 memcpy(This->palette9, device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256);
2475 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadTexture(IWineD3DSurface *iface, BOOL srgb_mode) {
2476 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2477 DWORD flag = srgb_mode ? SFLAG_INSRGBTEX : SFLAG_INTEXTURE;
2479 TRACE("iface %p, srgb %#x.\n", iface, srgb_mode);
2481 if (!(This->Flags & flag)) {
2482 TRACE("Reloading because surface is dirty\n");
2483 } else if(/* Reload: gl texture has ck, now no ckey is set OR */
2484 ((This->Flags & SFLAG_GLCKEY) && (!(This->CKeyFlags & WINEDDSD_CKSRCBLT))) ||
2485 /* Reload: vice versa OR */
2486 ((!(This->Flags & SFLAG_GLCKEY)) && (This->CKeyFlags & WINEDDSD_CKSRCBLT)) ||
2487 /* Also reload: Color key is active AND the color key has changed */
2488 ((This->CKeyFlags & WINEDDSD_CKSRCBLT) && (
2489 (This->glCKey.dwColorSpaceLowValue != This->SrcBltCKey.dwColorSpaceLowValue) ||
2490 (This->glCKey.dwColorSpaceHighValue != This->SrcBltCKey.dwColorSpaceHighValue)))) {
2491 TRACE("Reloading because of color keying\n");
2492 /* To perform the color key conversion we need a sysmem copy of
2493 * the surface. Make sure we have it
2496 surface_load_location(This, SFLAG_INSYSMEM, NULL);
2497 /* Make sure the texture is reloaded because of the color key change, this kills performance though :( */
2498 /* TODO: This is not necessarily needed with hw palettized texture support */
2499 surface_modify_location(This, SFLAG_INSYSMEM, TRUE);
2501 TRACE("surface is already in texture\n");
2505 /* Resources are placed in system RAM and do not need to be recreated when a device is lost.
2506 * These resources are not bound by device size or format restrictions. Because of this,
2507 * these resources cannot be accessed by the Direct3D device nor set as textures or render targets.
2508 * However, these resources can always be created, locked, and copied.
2510 if (This->resource.pool == WINED3DPOOL_SCRATCH )
2512 FIXME("(%p) Operation not supported for scratch textures\n",This);
2513 return WINED3DERR_INVALIDCALL;
2516 surface_load_location(This, flag, NULL /* no partial locking for textures yet */);
2518 if (!(This->Flags & SFLAG_DONOTFREE)) {
2519 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
2520 This->resource.allocatedMemory = NULL;
2521 This->resource.heapMemory = NULL;
2522 surface_modify_location(This, SFLAG_INSYSMEM, FALSE);
2528 /* Context activation is done by the caller. */
2529 static void WINAPI IWineD3DSurfaceImpl_BindTexture(IWineD3DSurface *iface, BOOL srgb)
2531 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2533 TRACE("iface %p, srgb %#x.\n", iface, srgb);
2535 if (This->container.type == WINED3D_CONTAINER_TEXTURE)
2537 TRACE("Passing to container.\n");
2538 IWineD3DBaseTexture_BindTexture((IWineD3DBaseTexture *)This->container.u.texture, srgb);
2544 TRACE("(%p) : Binding surface\n", This);
2546 name = srgb ? &This->texture_name_srgb : &This->texture_name;
2550 if (!This->texture_level)
2553 glGenTextures(1, name);
2554 checkGLcall("glGenTextures");
2555 TRACE("Surface %p given name %d\n", This, *name);
2557 glBindTexture(This->texture_target, *name);
2558 checkGLcall("glBindTexture");
2559 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2560 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)");
2561 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2562 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)");
2563 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
2564 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)");
2565 glTexParameteri(This->texture_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2566 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_MIN_FILTER, GL_NEAREST)");
2567 glTexParameteri(This->texture_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2568 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_MAG_FILTER, GL_NEAREST)");
2570 /* This is where we should be reducing the amount of GLMemoryUsed */
2572 /* Mipmap surfaces should have a base texture container */
2573 ERR("Mipmap surface has a glTexture bound to it!\n");
2576 glBindTexture(This->texture_target, *name);
2577 checkGLcall("glBindTexture");
2583 static HRESULT WINAPI IWineD3DSurfaceImpl_SetFormat(IWineD3DSurface *iface, enum wined3d_format_id format)
2585 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2588 TRACE("(%p) : Calling base function first\n", This);
2589 hr = IWineD3DBaseSurfaceImpl_SetFormat(iface, format);
2591 This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
2592 TRACE("(%p) : glFormat %d, glFormatInternal %d, glType %d\n", This, This->resource.format->glFormat,
2593 This->resource.format->glInternal, This->resource.format->glType);
2598 static HRESULT WINAPI IWineD3DSurfaceImpl_SetMem(IWineD3DSurface *iface, void *Mem) {
2599 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
2601 if(This->Flags & (SFLAG_LOCKED | SFLAG_DCINUSE)) {
2602 WARN("Surface is locked or the HDC is in use\n");
2603 return WINED3DERR_INVALIDCALL;
2606 if(Mem && Mem != This->resource.allocatedMemory) {
2607 void *release = NULL;
2609 /* Do I have to copy the old surface content? */
2610 if(This->Flags & SFLAG_DIBSECTION) {
2611 /* Release the DC. No need to hold the critical section for the update
2612 * Thread because this thread runs only on front buffers, but this method
2613 * fails for render targets in the check above.
2615 SelectObject(This->hDC, This->dib.holdbitmap);
2616 DeleteDC(This->hDC);
2617 /* Release the DIB section */
2618 DeleteObject(This->dib.DIBsection);
2619 This->dib.bitmap_data = NULL;
2620 This->resource.allocatedMemory = NULL;
2622 This->Flags &= ~SFLAG_DIBSECTION;
2623 } else if(!(This->Flags & SFLAG_USERPTR)) {
2624 release = This->resource.heapMemory;
2625 This->resource.heapMemory = NULL;
2627 This->resource.allocatedMemory = Mem;
2628 This->Flags |= SFLAG_USERPTR | SFLAG_INSYSMEM;
2630 /* Now the surface memory is most up do date. Invalidate drawable and texture */
2631 surface_modify_location(This, SFLAG_INSYSMEM, TRUE);
2633 /* For client textures opengl has to be notified */
2634 if (This->Flags & SFLAG_CLIENT)
2635 surface_release_client_storage(This);
2637 /* Now free the old memory if any */
2638 HeapFree(GetProcessHeap(), 0, release);
2640 else if (This->Flags & SFLAG_USERPTR)
2642 /* Map and GetDC will re-create the dib section and allocated memory. */
2643 This->resource.allocatedMemory = NULL;
2644 /* HeapMemory should be NULL already */
2645 if (This->resource.heapMemory)
2646 ERR("User pointer surface has heap memory allocated.\n");
2647 This->Flags &= ~SFLAG_USERPTR;
2649 if (This->Flags & SFLAG_CLIENT)
2650 surface_release_client_storage(This);
2655 void flip_surface(IWineD3DSurfaceImpl *front, IWineD3DSurfaceImpl *back) {
2657 /* Flip the surface contents */
2662 front->hDC = back->hDC;
2666 /* Flip the DIBsection */
2669 BOOL hasDib = front->Flags & SFLAG_DIBSECTION;
2670 tmp = front->dib.DIBsection;
2671 front->dib.DIBsection = back->dib.DIBsection;
2672 back->dib.DIBsection = tmp;
2674 if(back->Flags & SFLAG_DIBSECTION) front->Flags |= SFLAG_DIBSECTION;
2675 else front->Flags &= ~SFLAG_DIBSECTION;
2676 if(hasDib) back->Flags |= SFLAG_DIBSECTION;
2677 else back->Flags &= ~SFLAG_DIBSECTION;
2680 /* Flip the surface data */
2684 tmp = front->dib.bitmap_data;
2685 front->dib.bitmap_data = back->dib.bitmap_data;
2686 back->dib.bitmap_data = tmp;
2688 tmp = front->resource.allocatedMemory;
2689 front->resource.allocatedMemory = back->resource.allocatedMemory;
2690 back->resource.allocatedMemory = tmp;
2692 tmp = front->resource.heapMemory;
2693 front->resource.heapMemory = back->resource.heapMemory;
2694 back->resource.heapMemory = tmp;
2699 GLuint tmp_pbo = front->pbo;
2700 front->pbo = back->pbo;
2701 back->pbo = tmp_pbo;
2704 /* client_memory should not be different, but just in case */
2707 tmp = front->dib.client_memory;
2708 front->dib.client_memory = back->dib.client_memory;
2709 back->dib.client_memory = tmp;
2712 /* Flip the opengl texture */
2716 tmp = back->texture_name;
2717 back->texture_name = front->texture_name;
2718 front->texture_name = tmp;
2720 tmp = back->texture_name_srgb;
2721 back->texture_name_srgb = front->texture_name_srgb;
2722 front->texture_name_srgb = tmp;
2726 DWORD tmp_flags = back->Flags;
2727 back->Flags = front->Flags;
2728 front->Flags = tmp_flags;
2732 static HRESULT WINAPI IWineD3DSurfaceImpl_Flip(IWineD3DSurface *iface, IWineD3DSurface *override, DWORD Flags) {
2733 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2734 IWineD3DSwapChainImpl *swapchain = NULL;
2736 TRACE("(%p)->(%p,%x)\n", This, override, Flags);
2738 /* Flipping is only supported on RenderTargets and overlays*/
2739 if( !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_OVERLAY)) ) {
2740 WARN("Tried to flip a non-render target, non-overlay surface\n");
2741 return WINEDDERR_NOTFLIPPABLE;
2744 if(This->resource.usage & WINED3DUSAGE_OVERLAY) {
2745 flip_surface(This, (IWineD3DSurfaceImpl *) override);
2747 /* Update the overlay if it is visible */
2748 if(This->overlay_dest) {
2749 return IWineD3DSurface_DrawOverlay((IWineD3DSurface *) This);
2756 /* DDraw sets this for the X11 surfaces, so don't confuse the user
2757 * FIXME("(%p) Target override is not supported by now\n", This);
2758 * Additionally, it isn't really possible to support triple-buffering
2759 * properly on opengl at all
2763 if (This->container.type != WINED3D_CONTAINER_SWAPCHAIN)
2765 ERR("Flipped surface is not on a swapchain\n");
2766 return WINEDDERR_NOTFLIPPABLE;
2768 swapchain = This->container.u.swapchain;
2770 /* Just overwrite the swapchain presentation interval. This is ok because only ddraw apps can call Flip,
2771 * and only d3d8 and d3d9 apps specify the presentation interval
2773 if (!(Flags & (WINEDDFLIP_NOVSYNC | WINEDDFLIP_INTERVAL2 | WINEDDFLIP_INTERVAL3 | WINEDDFLIP_INTERVAL4)))
2775 /* Most common case first to avoid wasting time on all the other cases */
2776 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_ONE;
2777 } else if(Flags & WINEDDFLIP_NOVSYNC) {
2778 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
2779 } else if(Flags & WINEDDFLIP_INTERVAL2) {
2780 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_TWO;
2781 } else if(Flags & WINEDDFLIP_INTERVAL3) {
2782 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_THREE;
2784 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_FOUR;
2787 /* Flipping a OpenGL surface -> Use WineD3DDevice::Present */
2788 return IWineD3DSwapChain_Present((IWineD3DSwapChain *)swapchain,
2789 NULL, NULL, swapchain->win_handle, NULL, 0);
2792 /* Does a direct frame buffer -> texture copy. Stretching is done
2793 * with single pixel copy calls
2795 static void fb_copy_to_texture_direct(IWineD3DSurfaceImpl *dst_surface, IWineD3DSurfaceImpl *src_surface,
2796 const RECT *src_rect, const RECT *dst_rect_in, WINED3DTEXTUREFILTERTYPE Filter)
2798 IWineD3DDeviceImpl *device = dst_surface->resource.device;
2801 struct wined3d_context *context;
2802 BOOL upsidedown = FALSE;
2803 RECT dst_rect = *dst_rect_in;
2805 /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
2806 * glCopyTexSubImage is a bit picky about the parameters we pass to it
2808 if(dst_rect.top > dst_rect.bottom) {
2809 UINT tmp = dst_rect.bottom;
2810 dst_rect.bottom = dst_rect.top;
2815 context = context_acquire(device, src_surface);
2816 context_apply_blit_state(context, device);
2817 surface_internal_preload(dst_surface, SRGB_RGB);
2820 /* Bind the target texture */
2821 glBindTexture(dst_surface->texture_target, dst_surface->texture_name);
2822 checkGLcall("glBindTexture");
2823 if (surface_is_offscreen(src_surface))
2825 TRACE("Reading from an offscreen target\n");
2826 upsidedown = !upsidedown;
2827 glReadBuffer(device->offscreenBuffer);
2831 glReadBuffer(surface_get_gl_buffer(src_surface));
2833 checkGLcall("glReadBuffer");
2835 xrel = (float) (src_rect->right - src_rect->left) / (float) (dst_rect.right - dst_rect.left);
2836 yrel = (float) (src_rect->bottom - src_rect->top) / (float) (dst_rect.bottom - dst_rect.top);
2838 if ((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
2840 FIXME("Doing a pixel by pixel copy from the framebuffer to a texture, expect major performance issues\n");
2842 if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
2843 ERR("Texture filtering not supported in direct blit\n");
2846 else if ((Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT)
2847 && ((yrel - 1.0f < -eps) || (yrel - 1.0f > eps)))
2849 ERR("Texture filtering not supported in direct blit\n");
2853 && !((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
2854 && !((yrel - 1.0f < -eps) || (yrel - 1.0f > eps)))
2856 /* Upside down copy without stretching is nice, one glCopyTexSubImage call will do */
2858 glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
2859 dst_rect.left /*xoffset */, dst_rect.top /* y offset */,
2860 src_rect->left, src_surface->currentDesc.Height - src_rect->bottom,
2861 dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top);
2863 UINT yoffset = src_surface->currentDesc.Height - src_rect->top + dst_rect.top - 1;
2864 /* I have to process this row by row to swap the image,
2865 * otherwise it would be upside down, so stretching in y direction
2866 * doesn't cost extra time
2868 * However, stretching in x direction can be avoided if not necessary
2870 for(row = dst_rect.top; row < dst_rect.bottom; row++) {
2871 if ((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
2873 /* Well, that stuff works, but it's very slow.
2874 * find a better way instead
2878 for (col = dst_rect.left; col < dst_rect.right; ++col)
2880 glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
2881 dst_rect.left + col /* x offset */, row /* y offset */,
2882 src_rect->left + col * xrel, yoffset - (int) (row * yrel), 1, 1);
2887 glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
2888 dst_rect.left /* x offset */, row /* y offset */,
2889 src_rect->left, yoffset - (int) (row * yrel), dst_rect.right - dst_rect.left, 1);
2893 checkGLcall("glCopyTexSubImage2D");
2896 context_release(context);
2898 /* The texture is now most up to date - If the surface is a render target and has a drawable, this
2899 * path is never entered
2901 surface_modify_location(dst_surface, SFLAG_INTEXTURE, TRUE);
2904 /* Uses the hardware to stretch and flip the image */
2905 static void fb_copy_to_texture_hwstretch(IWineD3DSurfaceImpl *dst_surface, IWineD3DSurfaceImpl *src_surface,
2906 const RECT *src_rect, const RECT *dst_rect_in, WINED3DTEXTUREFILTERTYPE Filter)
2908 IWineD3DDeviceImpl *device = dst_surface->resource.device;
2909 GLuint src, backup = 0;
2910 IWineD3DSwapChainImpl *src_swapchain = NULL;
2911 float left, right, top, bottom; /* Texture coordinates */
2912 UINT fbwidth = src_surface->currentDesc.Width;
2913 UINT fbheight = src_surface->currentDesc.Height;
2914 struct wined3d_context *context;
2915 GLenum drawBuffer = GL_BACK;
2916 GLenum texture_target;
2917 BOOL noBackBufferBackup;
2919 BOOL upsidedown = FALSE;
2920 RECT dst_rect = *dst_rect_in;
2922 TRACE("Using hwstretch blit\n");
2923 /* Activate the Proper context for reading from the source surface, set it up for blitting */
2924 context = context_acquire(device, src_surface);
2925 context_apply_blit_state(context, device);
2926 surface_internal_preload(dst_surface, SRGB_RGB);
2928 src_offscreen = surface_is_offscreen(src_surface);
2929 noBackBufferBackup = src_offscreen && wined3d_settings.offscreen_rendering_mode == ORM_FBO;
2930 if (!noBackBufferBackup && !src_surface->texture_name)
2932 /* Get it a description */
2933 surface_internal_preload(src_surface, SRGB_RGB);
2937 /* Try to use an aux buffer for drawing the rectangle. This way it doesn't need restoring.
2938 * This way we don't have to wait for the 2nd readback to finish to leave this function.
2940 if (context->aux_buffers >= 2)
2942 /* Got more than one aux buffer? Use the 2nd aux buffer */
2943 drawBuffer = GL_AUX1;
2945 else if ((!src_offscreen || device->offscreenBuffer == GL_BACK) && context->aux_buffers >= 1)
2947 /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
2948 drawBuffer = GL_AUX0;
2951 if(noBackBufferBackup) {
2952 glGenTextures(1, &backup);
2953 checkGLcall("glGenTextures");
2954 glBindTexture(GL_TEXTURE_2D, backup);
2955 checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
2956 texture_target = GL_TEXTURE_2D;
2958 /* Backup the back buffer and copy the source buffer into a texture to draw an upside down stretched quad. If
2959 * we are reading from the back buffer, the backup can be used as source texture
2961 texture_target = src_surface->texture_target;
2962 glBindTexture(texture_target, src_surface->texture_name);
2963 checkGLcall("glBindTexture(texture_target, src_surface->texture_name)");
2964 glEnable(texture_target);
2965 checkGLcall("glEnable(texture_target)");
2967 /* For now invalidate the texture copy of the back buffer. Drawable and sysmem copy are untouched */
2968 src_surface->Flags &= ~SFLAG_INTEXTURE;
2971 /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
2972 * glCopyTexSubImage is a bit picky about the parameters we pass to it
2974 if(dst_rect.top > dst_rect.bottom) {
2975 UINT tmp = dst_rect.bottom;
2976 dst_rect.bottom = dst_rect.top;
2983 TRACE("Reading from an offscreen target\n");
2984 upsidedown = !upsidedown;
2985 glReadBuffer(device->offscreenBuffer);
2989 glReadBuffer(surface_get_gl_buffer(src_surface));
2992 /* TODO: Only back up the part that will be overwritten */
2993 glCopyTexSubImage2D(texture_target, 0,
2994 0, 0 /* read offsets */,
2999 checkGLcall("glCopyTexSubImage2D");
3001 /* No issue with overriding these - the sampler is dirty due to blit usage */
3002 glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER,
3003 wined3d_gl_mag_filter(magLookup, Filter));
3004 checkGLcall("glTexParameteri");
3005 glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER,
3006 wined3d_gl_min_mip_filter(minMipLookup, Filter, WINED3DTEXF_NONE));
3007 checkGLcall("glTexParameteri");
3009 if (src_surface->container.type == WINED3D_CONTAINER_SWAPCHAIN)
3010 src_swapchain = src_surface->container.u.swapchain;
3011 if (!src_swapchain || src_surface == src_swapchain->back_buffers[0])
3013 src = backup ? backup : src_surface->texture_name;
3017 glReadBuffer(GL_FRONT);
3018 checkGLcall("glReadBuffer(GL_FRONT)");
3020 glGenTextures(1, &src);
3021 checkGLcall("glGenTextures(1, &src)");
3022 glBindTexture(GL_TEXTURE_2D, src);
3023 checkGLcall("glBindTexture(GL_TEXTURE_2D, src)");
3025 /* TODO: Only copy the part that will be read. Use src_rect->left, src_rect->bottom as origin, but with the width watch
3026 * out for power of 2 sizes
3028 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, src_surface->pow2Width,
3029 src_surface->pow2Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
3030 checkGLcall("glTexImage2D");
3031 glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
3032 0, 0 /* read offsets */,
3037 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
3038 checkGLcall("glTexParameteri");
3039 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
3040 checkGLcall("glTexParameteri");
3042 glReadBuffer(GL_BACK);
3043 checkGLcall("glReadBuffer(GL_BACK)");
3045 if(texture_target != GL_TEXTURE_2D) {
3046 glDisable(texture_target);
3047 glEnable(GL_TEXTURE_2D);
3048 texture_target = GL_TEXTURE_2D;
3051 checkGLcall("glEnd and previous");
3053 left = src_rect->left;
3054 right = src_rect->right;
3058 top = src_surface->currentDesc.Height - src_rect->top;
3059 bottom = src_surface->currentDesc.Height - src_rect->bottom;
3063 top = src_surface->currentDesc.Height - src_rect->bottom;
3064 bottom = src_surface->currentDesc.Height - src_rect->top;
3067 if (src_surface->Flags & SFLAG_NORMCOORD)
3069 left /= src_surface->pow2Width;
3070 right /= src_surface->pow2Width;
3071 top /= src_surface->pow2Height;
3072 bottom /= src_surface->pow2Height;
3075 /* draw the source texture stretched and upside down. The correct surface is bound already */
3076 glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
3077 glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
3079 context_set_draw_buffer(context, drawBuffer);
3080 glReadBuffer(drawBuffer);
3084 glTexCoord2f(left, bottom);
3085 glVertex2i(0, fbheight);
3088 glTexCoord2f(left, top);
3089 glVertex2i(0, fbheight - dst_rect.bottom - dst_rect.top);
3092 glTexCoord2f(right, top);
3093 glVertex2i(dst_rect.right - dst_rect.left, fbheight - dst_rect.bottom - dst_rect.top);
3096 glTexCoord2f(right, bottom);
3097 glVertex2i(dst_rect.right - dst_rect.left, fbheight);
3099 checkGLcall("glEnd and previous");
3101 if (texture_target != dst_surface->texture_target)
3103 glDisable(texture_target);
3104 glEnable(dst_surface->texture_target);
3105 texture_target = dst_surface->texture_target;
3108 /* Now read the stretched and upside down image into the destination texture */
3109 glBindTexture(texture_target, dst_surface->texture_name);
3110 checkGLcall("glBindTexture");
3111 glCopyTexSubImage2D(texture_target,
3113 dst_rect.left, dst_rect.top, /* xoffset, yoffset */
3114 0, 0, /* We blitted the image to the origin */
3115 dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top);
3116 checkGLcall("glCopyTexSubImage2D");
3118 if(drawBuffer == GL_BACK) {
3119 /* Write the back buffer backup back */
3121 if(texture_target != GL_TEXTURE_2D) {
3122 glDisable(texture_target);
3123 glEnable(GL_TEXTURE_2D);
3124 texture_target = GL_TEXTURE_2D;
3126 glBindTexture(GL_TEXTURE_2D, backup);
3127 checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
3131 if (texture_target != src_surface->texture_target)
3133 glDisable(texture_target);
3134 glEnable(src_surface->texture_target);
3135 texture_target = src_surface->texture_target;
3137 glBindTexture(src_surface->texture_target, src_surface->texture_name);
3138 checkGLcall("glBindTexture(src_surface->texture_target, src_surface->texture_name)");
3143 glTexCoord2f(0.0f, (float)fbheight / (float)src_surface->pow2Height);
3147 glTexCoord2f(0.0f, 0.0f);
3148 glVertex2i(0, fbheight);
3151 glTexCoord2f((float)fbwidth / (float)src_surface->pow2Width, 0.0f);
3152 glVertex2i(fbwidth, src_surface->currentDesc.Height);
3155 glTexCoord2f((float)fbwidth / (float)src_surface->pow2Width,
3156 (float)fbheight / (float)src_surface->pow2Height);
3157 glVertex2i(fbwidth, 0);
3160 glDisable(texture_target);
3161 checkGLcall("glDisable(texture_target)");
3164 if (src != src_surface->texture_name && src != backup)
3166 glDeleteTextures(1, &src);
3167 checkGLcall("glDeleteTextures(1, &src)");
3170 glDeleteTextures(1, &backup);
3171 checkGLcall("glDeleteTextures(1, &backup)");
3176 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
3178 context_release(context);
3180 /* The texture is now most up to date - If the surface is a render target and has a drawable, this
3181 * path is never entered
3183 surface_modify_location(dst_surface, SFLAG_INTEXTURE, TRUE);
3186 /* Until the blit_shader is ready, define some prototypes here. */
3187 static BOOL fbo_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
3188 const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool, const struct wined3d_format *src_format,
3189 const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool, const struct wined3d_format *dst_format);
3191 /* Front buffer coordinates are always full screen coordinates, but our GL
3192 * drawable is limited to the window's client area. The sysmem and texture
3193 * copies do have the full screen size. Note that GL has a bottom-left
3194 * origin, while D3D has a top-left origin. */
3195 void surface_translate_frontbuffer_coords(IWineD3DSurfaceImpl *surface, HWND window, RECT *rect)
3197 POINT offset = {0, surface->currentDesc.Height};
3200 GetClientRect(window, &windowsize);
3201 offset.y -= windowsize.bottom - windowsize.top;
3202 ScreenToClient(window, &offset);
3203 OffsetRect(rect, offset.x, offset.y);
3206 static BOOL surface_is_full_rect(IWineD3DSurfaceImpl *surface, const RECT *r)
3208 if ((r->left && r->right) || abs(r->right - r->left) != surface->currentDesc.Width)
3210 if ((r->top && r->bottom) || abs(r->bottom - r->top) != surface->currentDesc.Height)
3215 /* blit between surface locations. onscreen on different swapchains is not supported.
3216 * depth / stencil is not supported. */
3217 static void surface_blt_fbo(IWineD3DDeviceImpl *device, const WINED3DTEXTUREFILTERTYPE filter,
3218 IWineD3DSurfaceImpl *src_surface, DWORD src_location, const RECT *src_rect_in,
3219 IWineD3DSurfaceImpl *dst_surface, DWORD dst_location, const RECT *dst_rect_in)
3221 const struct wined3d_gl_info *gl_info;
3222 struct wined3d_context *context;
3223 RECT src_rect, dst_rect;
3226 TRACE("device %p, filter %s,\n", device, debug_d3dtexturefiltertype(filter));
3227 TRACE("src_surface %p, src_location %s, src_rect %s,\n",
3228 src_surface, debug_surflocation(src_location), wine_dbgstr_rect(src_rect_in));
3229 TRACE("dst_surface %p, dst_location %s, dst_rect %s.\n",
3230 dst_surface, debug_surflocation(dst_location), wine_dbgstr_rect(dst_rect_in));
3232 src_rect = *src_rect_in;
3233 dst_rect = *dst_rect_in;
3237 case WINED3DTEXF_LINEAR:
3238 gl_filter = GL_LINEAR;
3242 FIXME("Unsupported filter mode %s (%#x).\n", debug_d3dtexturefiltertype(filter), filter);
3243 case WINED3DTEXF_NONE:
3244 case WINED3DTEXF_POINT:
3245 gl_filter = GL_NEAREST;
3249 if (src_location == SFLAG_INDRAWABLE && surface_is_offscreen(src_surface))
3250 src_location = SFLAG_INTEXTURE;
3251 if (dst_location == SFLAG_INDRAWABLE && surface_is_offscreen(dst_surface))
3252 dst_location = SFLAG_INTEXTURE;
3254 /* Make sure the locations are up-to-date. Loading the destination
3255 * surface isn't required if the entire surface is overwritten. (And is
3256 * in fact harmful if we're being called by surface_load_location() with
3257 * the purpose of loading the destination surface.) */
3258 surface_load_location(src_surface, src_location, NULL);
3259 if (!surface_is_full_rect(dst_surface, &dst_rect))
3260 surface_load_location(dst_surface, dst_location, NULL);
3262 if (src_location == SFLAG_INDRAWABLE) context = context_acquire(device, src_surface);
3263 else if (dst_location == SFLAG_INDRAWABLE) context = context_acquire(device, dst_surface);
3264 else context = context_acquire(device, NULL);
3266 if (!context->valid)
3268 context_release(context);
3269 WARN("Invalid context, skipping blit.\n");
3273 gl_info = context->gl_info;
3275 if (src_location == SFLAG_INDRAWABLE)
3277 GLenum buffer = surface_get_gl_buffer(src_surface);
3279 TRACE("Source surface %p is onscreen.\n", src_surface);
3281 if (buffer == GL_FRONT)
3282 surface_translate_frontbuffer_coords(src_surface, context->win_handle, &src_rect);
3284 src_rect.top = src_surface->currentDesc.Height - src_rect.top;
3285 src_rect.bottom = src_surface->currentDesc.Height - src_rect.bottom;
3288 context_bind_fbo(context, GL_READ_FRAMEBUFFER, NULL);
3289 glReadBuffer(buffer);
3290 checkGLcall("glReadBuffer()");
3294 TRACE("Source surface %p is offscreen.\n", src_surface);
3296 context_apply_fbo_state_blit(context, GL_READ_FRAMEBUFFER, src_surface, NULL, src_location);
3297 glReadBuffer(GL_COLOR_ATTACHMENT0);
3298 checkGLcall("glReadBuffer()");
3302 if (dst_location == SFLAG_INDRAWABLE)
3304 GLenum buffer = surface_get_gl_buffer(dst_surface);
3306 TRACE("Destination surface %p is onscreen.\n", dst_surface);
3308 if (buffer == GL_FRONT)
3309 surface_translate_frontbuffer_coords(dst_surface, context->win_handle, &dst_rect);
3311 dst_rect.top = dst_surface->currentDesc.Height - dst_rect.top;
3312 dst_rect.bottom = dst_surface->currentDesc.Height - dst_rect.bottom;
3315 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, NULL);
3316 context_set_draw_buffer(context, buffer);
3320 TRACE("Destination surface %p is offscreen.\n", dst_surface);
3323 context_apply_fbo_state_blit(context, GL_DRAW_FRAMEBUFFER, dst_surface, NULL, dst_location);
3324 context_set_draw_buffer(context, GL_COLOR_ATTACHMENT0);
3327 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
3328 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
3329 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
3330 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
3331 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
3333 glDisable(GL_SCISSOR_TEST);
3334 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
3336 gl_info->fbo_ops.glBlitFramebuffer(src_rect.left, src_rect.top, src_rect.right, src_rect.bottom,
3337 dst_rect.left, dst_rect.top, dst_rect.right, dst_rect.bottom, GL_COLOR_BUFFER_BIT, gl_filter);
3338 checkGLcall("glBlitFramebuffer()");
3342 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
3344 context_release(context);
3347 /* Do not call while under the GL lock. */
3348 HRESULT surface_color_fill(IWineD3DSurfaceImpl *s, const RECT *rect, const WINED3DCOLORVALUE *color)
3350 IWineD3DDeviceImpl *device = s->resource.device;
3351 const struct blit_shader *blitter;
3353 blitter = wined3d_select_blitter(&device->adapter->gl_info, BLIT_OP_COLOR_FILL,
3354 NULL, 0, 0, NULL, rect, s->resource.usage, s->resource.pool, s->resource.format);
3357 FIXME("No blitter is capable of performing the requested color fill operation.\n");
3358 return WINED3DERR_INVALIDCALL;
3361 return blitter->color_fill(device, s, rect, color);
3364 /* Not called from the VTable */
3365 /* Do not call while under the GL lock. */
3366 static HRESULT IWineD3DSurfaceImpl_BltOverride(IWineD3DSurfaceImpl *dst_surface, const RECT *DestRect,
3367 IWineD3DSurfaceImpl *src_surface, const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx,
3368 WINED3DTEXTUREFILTERTYPE Filter)
3370 IWineD3DDeviceImpl *device = dst_surface->resource.device;
3371 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3372 IWineD3DSwapChainImpl *srcSwapchain = NULL, *dstSwapchain = NULL;
3373 RECT dst_rect, src_rect;
3375 TRACE("dst_surface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, blt_fx %p, filter %s.\n",
3376 dst_surface, wine_dbgstr_rect(DestRect), src_surface, wine_dbgstr_rect(SrcRect),
3377 Flags, DDBltFx, debug_d3dtexturefiltertype(Filter));
3379 /* Get the swapchain. One of the surfaces has to be a primary surface */
3380 if (dst_surface->resource.pool == WINED3DPOOL_SYSTEMMEM)
3382 WARN("Destination is in sysmem, rejecting gl blt\n");
3383 return WINED3DERR_INVALIDCALL;
3386 if (dst_surface->container.type == WINED3D_CONTAINER_SWAPCHAIN)
3387 dstSwapchain = dst_surface->container.u.swapchain;
3391 if (src_surface->resource.pool == WINED3DPOOL_SYSTEMMEM)
3393 WARN("Src is in sysmem, rejecting gl blt\n");
3394 return WINED3DERR_INVALIDCALL;
3397 if (src_surface->container.type == WINED3D_CONTAINER_SWAPCHAIN)
3398 srcSwapchain = src_surface->container.u.swapchain;
3401 /* Early sort out of cases where no render target is used */
3402 if (!dstSwapchain && !srcSwapchain
3403 && src_surface != device->render_targets[0]
3404 && dst_surface != device->render_targets[0])
3406 TRACE("No surface is render target, not using hardware blit.\n");
3407 return WINED3DERR_INVALIDCALL;
3410 /* No destination color keying supported */
3411 if(Flags & (WINEDDBLT_KEYDEST | WINEDDBLT_KEYDESTOVERRIDE)) {
3412 /* Can we support that with glBlendFunc if blitting to the frame buffer? */
3413 TRACE("Destination color key not supported in accelerated Blit, falling back to software\n");
3414 return WINED3DERR_INVALIDCALL;
3417 surface_get_rect(dst_surface, DestRect, &dst_rect);
3418 if (src_surface) surface_get_rect(src_surface, SrcRect, &src_rect);
3420 /* The only case where both surfaces on a swapchain are supported is a back buffer -> front buffer blit on the same swapchain */
3421 if (dstSwapchain && dstSwapchain == srcSwapchain && dstSwapchain->back_buffers
3422 && dst_surface == dstSwapchain->front_buffer
3423 && src_surface == dstSwapchain->back_buffers[0])
3425 /* Half-Life does a Blt from the back buffer to the front buffer,
3426 * Full surface size, no flags... Use present instead
3428 * This path will only be entered for d3d7 and ddraw apps, because d3d8/9 offer no way to blit TO the front buffer
3431 /* Check rects - IWineD3DDevice_Present doesn't handle them */
3434 TRACE("Looking if a Present can be done...\n");
3435 /* Source Rectangle must be full surface */
3436 if (src_rect.left || src_rect.top
3437 || src_rect.right != src_surface->currentDesc.Width
3438 || src_rect.bottom != src_surface->currentDesc.Height)
3440 TRACE("No, Source rectangle doesn't match\n");
3444 /* No stretching may occur */
3445 if(src_rect.right != dst_rect.right - dst_rect.left ||
3446 src_rect.bottom != dst_rect.bottom - dst_rect.top) {
3447 TRACE("No, stretching is done\n");
3451 /* Destination must be full surface or match the clipping rectangle */
3452 if (dst_surface->clipper && ((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd)
3456 GetClientRect(((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd, &cliprect);
3457 pos[0].x = dst_rect.left;
3458 pos[0].y = dst_rect.top;
3459 pos[1].x = dst_rect.right;
3460 pos[1].y = dst_rect.bottom;
3461 MapWindowPoints(GetDesktopWindow(), ((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd, pos, 2);
3463 if(pos[0].x != cliprect.left || pos[0].y != cliprect.top ||
3464 pos[1].x != cliprect.right || pos[1].y != cliprect.bottom)
3466 TRACE("No, dest rectangle doesn't match(clipper)\n");
3467 TRACE("Clip rect at %s\n", wine_dbgstr_rect(&cliprect));
3468 TRACE("Blt dest: %s\n", wine_dbgstr_rect(&dst_rect));
3472 else if (dst_rect.left || dst_rect.top
3473 || dst_rect.right != dst_surface->currentDesc.Width
3474 || dst_rect.bottom != dst_surface->currentDesc.Height)
3476 TRACE("No, dest rectangle doesn't match(surface size)\n");
3482 /* These flags are unimportant for the flag check, remove them */
3483 if (!(Flags & ~(WINEDDBLT_DONOTWAIT | WINEDDBLT_WAIT)))
3485 WINED3DSWAPEFFECT orig_swap = dstSwapchain->presentParms.SwapEffect;
3487 /* The idea behind this is that a glReadPixels and a glDrawPixels call
3488 * take very long, while a flip is fast.
3489 * This applies to Half-Life, which does such Blts every time it finished
3490 * a frame, and to Prince of Persia 3D, which uses this to draw at least the main
3491 * menu. This is also used by all apps when they do windowed rendering
3493 * The problem is that flipping is not really the same as copying. After a
3494 * Blt the front buffer is a copy of the back buffer, and the back buffer is
3495 * untouched. Therefore it's necessary to override the swap effect
3496 * and to set it back after the flip.
3498 * Windowed Direct3D < 7 apps do the same. The D3D7 sdk demos are nice
3502 dstSwapchain->presentParms.SwapEffect = WINED3DSWAPEFFECT_COPY;
3503 dstSwapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
3505 TRACE("Full screen back buffer -> front buffer blt, performing a flip instead\n");
3506 IWineD3DSwapChain_Present((IWineD3DSwapChain *)dstSwapchain,
3507 NULL, NULL, dstSwapchain->win_handle, NULL, 0);
3509 dstSwapchain->presentParms.SwapEffect = orig_swap;
3516 TRACE("Unsupported blit between buffers on the same swapchain\n");
3517 return WINED3DERR_INVALIDCALL;
3518 } else if(dstSwapchain && dstSwapchain == srcSwapchain) {
3519 FIXME("Implement hardware blit between two surfaces on the same swapchain\n");
3520 return WINED3DERR_INVALIDCALL;
3521 } else if(dstSwapchain && srcSwapchain) {
3522 FIXME("Implement hardware blit between two different swapchains\n");
3523 return WINED3DERR_INVALIDCALL;
3525 else if (dstSwapchain)
3527 /* Handled with regular texture -> swapchain blit */
3528 if (src_surface == device->render_targets[0])
3529 TRACE("Blit from active render target to a swapchain\n");
3531 else if (srcSwapchain && dst_surface == device->render_targets[0])
3533 FIXME("Implement blit from a swapchain to the active render target\n");
3534 return WINED3DERR_INVALIDCALL;
3537 if ((srcSwapchain || src_surface == device->render_targets[0]) && !dstSwapchain)
3539 /* Blit from render target to texture */
3542 /* P8 read back is not implemented */
3543 if (src_surface->resource.format->id == WINED3DFMT_P8_UINT
3544 || dst_surface->resource.format->id == WINED3DFMT_P8_UINT)
3546 TRACE("P8 read back not supported by frame buffer to texture blit\n");
3547 return WINED3DERR_INVALIDCALL;
3550 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3551 TRACE("Color keying not supported by frame buffer to texture blit\n");
3552 return WINED3DERR_INVALIDCALL;
3553 /* Destination color key is checked above */
3556 if(dst_rect.right - dst_rect.left != src_rect.right - src_rect.left) {
3562 /* Blt is a pretty powerful call, while glCopyTexSubImage2D is not. glCopyTexSubImage cannot
3563 * flip the image nor scale it.
3565 * -> If the app asks for a unscaled, upside down copy, just perform one glCopyTexSubImage2D call
3566 * -> If the app wants a image width an unscaled width, copy it line per line
3567 * -> If the app wants a image that is scaled on the x axis, and the destination rectangle is smaller
3568 * than the frame buffer, draw an upside down scaled image onto the fb, read it back and restore the
3569 * back buffer. This is slower than reading line per line, thus not used for flipping
3570 * -> If the app wants a scaled image with a dest rect that is bigger than the fb, it has to be copied
3573 * If EXT_framebuffer_blit is supported that can be used instead. Note that EXT_framebuffer_blit implies
3574 * FBO support, so it doesn't really make sense to try and make it work with different offscreen rendering
3577 if (fbo_blit_supported(gl_info, BLIT_OP_BLIT,
3578 &src_rect, src_surface->resource.usage, src_surface->resource.pool, src_surface->resource.format,
3579 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool, dst_surface->resource.format))
3581 surface_blt_fbo(device, Filter,
3582 src_surface, SFLAG_INDRAWABLE, &src_rect,
3583 dst_surface, SFLAG_INDRAWABLE, &dst_rect);
3584 surface_modify_location(dst_surface, SFLAG_INDRAWABLE, TRUE);
3586 else if (!stretchx || dst_rect.right - dst_rect.left > src_surface->currentDesc.Width
3587 || dst_rect.bottom - dst_rect.top > src_surface->currentDesc.Height)
3589 TRACE("No stretching in x direction, using direct framebuffer -> texture copy\n");
3590 fb_copy_to_texture_direct(dst_surface, src_surface, &src_rect, &dst_rect, Filter);
3592 TRACE("Using hardware stretching to flip / stretch the texture\n");
3593 fb_copy_to_texture_hwstretch(dst_surface, src_surface, &src_rect, &dst_rect, Filter);
3596 if (!(dst_surface->Flags & SFLAG_DONOTFREE))
3598 HeapFree(GetProcessHeap(), 0, dst_surface->resource.heapMemory);
3599 dst_surface->resource.allocatedMemory = NULL;
3600 dst_surface->resource.heapMemory = NULL;
3604 dst_surface->Flags &= ~SFLAG_INSYSMEM;
3609 else if (src_surface)
3611 /* Blit from offscreen surface to render target */
3612 DWORD oldCKeyFlags = src_surface->CKeyFlags;
3613 WINEDDCOLORKEY oldBltCKey = src_surface->SrcBltCKey;
3614 struct wined3d_context *context;
3616 TRACE("Blt from surface %p to rendertarget %p\n", src_surface, dst_surface);
3618 if (!(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE))
3619 && fbo_blit_supported(gl_info, BLIT_OP_BLIT,
3620 &src_rect, src_surface->resource.usage, src_surface->resource.pool,
3621 src_surface->resource.format,
3622 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3623 dst_surface->resource.format))
3625 TRACE("Using surface_blt_fbo.\n");
3626 /* The source is always a texture, but never the currently active render target, and the texture
3627 * contents are never upside down. */
3628 surface_blt_fbo(device, Filter,
3629 src_surface, SFLAG_INDRAWABLE, &src_rect,
3630 dst_surface, SFLAG_INDRAWABLE, &dst_rect);
3631 surface_modify_location(dst_surface, SFLAG_INDRAWABLE, TRUE);
3635 if (!(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE))
3636 && arbfp_blit.blit_supported(gl_info, BLIT_OP_BLIT,
3637 &src_rect, src_surface->resource.usage, src_surface->resource.pool,
3638 src_surface->resource.format,
3639 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3640 dst_surface->resource.format))
3642 return arbfp_blit_surface(device, src_surface, &src_rect, dst_surface, &dst_rect, BLIT_OP_BLIT, Filter);
3645 /* Color keying: Check if we have to do a color keyed blt,
3646 * and if not check if a color key is activated.
3648 * Just modify the color keying parameters in the surface and restore them afterwards
3649 * The surface keeps track of the color key last used to load the opengl surface.
3650 * PreLoad will catch the change to the flags and color key and reload if necessary.
3652 if(Flags & WINEDDBLT_KEYSRC) {
3653 /* Use color key from surface */
3654 } else if(Flags & WINEDDBLT_KEYSRCOVERRIDE) {
3655 /* Use color key from DDBltFx */
3656 src_surface->CKeyFlags |= WINEDDSD_CKSRCBLT;
3657 src_surface->SrcBltCKey = DDBltFx->ddckSrcColorkey;
3659 /* Do not use color key */
3660 src_surface->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
3663 /* Now load the surface */
3664 surface_internal_preload(src_surface, SRGB_RGB);
3666 /* Activate the destination context, set it up for blitting */
3667 context = context_acquire(device, dst_surface);
3668 context_apply_blit_state(context, device);
3670 if (dstSwapchain && dst_surface == dstSwapchain->front_buffer)
3671 surface_translate_frontbuffer_coords(dst_surface, context->win_handle, &dst_rect);
3672 else if (surface_is_offscreen(dst_surface))
3674 dst_rect.top = dst_surface->currentDesc.Height - dst_rect.top;
3675 dst_rect.bottom = dst_surface->currentDesc.Height - dst_rect.bottom;
3678 if (!device->blitter->blit_supported(gl_info, BLIT_OP_BLIT,
3679 &src_rect, src_surface->resource.usage, src_surface->resource.pool, src_surface->resource.format,
3680 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool, dst_surface->resource.format))
3682 FIXME("Unsupported blit operation falling back to software\n");
3683 return WINED3DERR_INVALIDCALL;
3686 device->blitter->set_shader((IWineD3DDevice *)device, src_surface);
3690 /* This is for color keying */
3691 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3692 glEnable(GL_ALPHA_TEST);
3693 checkGLcall("glEnable(GL_ALPHA_TEST)");
3695 /* When the primary render target uses P8, the alpha component contains the palette index.
3696 * Which means that the colorkey is one of the palette entries. In other cases pixels that
3697 * should be masked away have alpha set to 0. */
3698 if (primary_render_target_is_p8(device))
3699 glAlphaFunc(GL_NOTEQUAL, (float)src_surface->SrcBltCKey.dwColorSpaceLowValue / 256.0f);
3701 glAlphaFunc(GL_NOTEQUAL, 0.0f);
3702 checkGLcall("glAlphaFunc");
3704 glDisable(GL_ALPHA_TEST);
3705 checkGLcall("glDisable(GL_ALPHA_TEST)");
3708 /* Draw a textured quad
3710 draw_textured_quad(src_surface, &src_rect, &dst_rect, Filter);
3712 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3713 glDisable(GL_ALPHA_TEST);
3714 checkGLcall("glDisable(GL_ALPHA_TEST)");
3717 /* Restore the color key parameters */
3718 src_surface->CKeyFlags = oldCKeyFlags;
3719 src_surface->SrcBltCKey = oldBltCKey;
3723 /* Leave the opengl state valid for blitting */
3724 device->blitter->unset_shader((IWineD3DDevice *)device);
3726 if (wined3d_settings.strict_draw_ordering || (dstSwapchain
3727 && (dst_surface == dstSwapchain->front_buffer
3728 || dstSwapchain->num_contexts > 1)))
3729 wglFlush(); /* Flush to ensure ordering across contexts. */
3731 context_release(context);
3733 /* TODO: If the surface is locked often, perform the Blt in software on the memory instead */
3734 /* The surface is now in the drawable. On onscreen surfaces or without fbos the texture
3737 surface_modify_location(dst_surface, SFLAG_INDRAWABLE, TRUE);
3743 /* Source-Less Blit to render target */
3744 if (Flags & WINEDDBLT_COLORFILL)
3746 WINED3DCOLORVALUE color;
3748 TRACE("Colorfill\n");
3750 /* The color as given in the Blt function is in the surface format. */
3751 if (!surface_convert_color_to_float(dst_surface, DDBltFx->u5.dwFillColor, &color))
3752 return WINED3DERR_INVALIDCALL;
3754 return surface_color_fill(dst_surface, &dst_rect, &color);
3758 /* Default: Fall back to the generic blt. Not an error, a TRACE is enough */
3759 TRACE("Didn't find any usable render target setup for hw blit, falling back to software\n");
3760 return WINED3DERR_INVALIDCALL;
3763 static HRESULT IWineD3DSurfaceImpl_BltZ(IWineD3DSurfaceImpl *This, const RECT *DestRect,
3764 IWineD3DSurface *src_surface, const RECT *src_rect, DWORD Flags, const WINEDDBLTFX *DDBltFx)
3766 IWineD3DDeviceImpl *device = This->resource.device;
3769 if (Flags & WINEDDBLT_DEPTHFILL)
3771 switch (This->resource.format->id)
3773 case WINED3DFMT_D16_UNORM:
3774 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000ffff;
3776 case WINED3DFMT_S1_UINT_D15_UNORM:
3777 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00007fff;
3779 case WINED3DFMT_D24_UNORM_S8_UINT:
3780 case WINED3DFMT_X8D24_UNORM:
3781 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00ffffff;
3783 case WINED3DFMT_D32_UNORM:
3784 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0xffffffff;
3788 ERR("Unexpected format for depth fill: %s.\n", debug_d3dformat(This->resource.format->id));
3791 return IWineD3DDevice_Clear((IWineD3DDevice *)device, DestRect ? 1 : 0, DestRect,
3792 WINED3DCLEAR_ZBUFFER, 0x00000000, depth, 0x00000000);
3795 FIXME("(%p): Unsupp depthstencil blit\n", This);
3796 return WINED3DERR_INVALIDCALL;
3799 static HRESULT WINAPI IWineD3DSurfaceImpl_Blt(IWineD3DSurface *iface, const RECT *DestRect,
3800 IWineD3DSurface *src_surface, const RECT *SrcRect, DWORD Flags,
3801 const WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter)
3803 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3804 IWineD3DSurfaceImpl *src = (IWineD3DSurfaceImpl *)src_surface;
3805 IWineD3DDeviceImpl *device = This->resource.device;
3807 TRACE("iface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, fx %p, filter %s.\n",
3808 iface, wine_dbgstr_rect(DestRect), src_surface, wine_dbgstr_rect(SrcRect),
3809 Flags, DDBltFx, debug_d3dtexturefiltertype(Filter));
3810 TRACE("Usage is %s.\n", debug_d3dusage(This->resource.usage));
3812 if ((This->Flags & SFLAG_LOCKED) || (src && (src->Flags & SFLAG_LOCKED)))
3814 WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3815 return WINEDDERR_SURFACEBUSY;
3818 /* Accessing the depth stencil is supposed to fail between a BeginScene and EndScene pair,
3819 * except depth blits, which seem to work
3821 if (This == device->depth_stencil || (src && src == device->depth_stencil))
3823 if (device->inScene && !(Flags & WINEDDBLT_DEPTHFILL))
3825 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3826 return WINED3DERR_INVALIDCALL;
3828 else if (SUCCEEDED(IWineD3DSurfaceImpl_BltZ(This, DestRect, src_surface, SrcRect, Flags, DDBltFx)))
3830 TRACE("Z Blit override handled the blit\n");
3835 /* Special cases for RenderTargets */
3836 if ((This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3837 || (src && (src->resource.usage & WINED3DUSAGE_RENDERTARGET)))
3839 if (SUCCEEDED(IWineD3DSurfaceImpl_BltOverride(This, DestRect, src, SrcRect, Flags, DDBltFx, Filter)))
3843 /* For the rest call the X11 surface implementation.
3844 * For RenderTargets this should be implemented OpenGL accelerated in BltOverride,
3845 * other Blts are rather rare. */
3846 return IWineD3DBaseSurfaceImpl_Blt(iface, DestRect, src_surface, SrcRect, Flags, DDBltFx, Filter);
3849 static HRESULT WINAPI IWineD3DSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty,
3850 IWineD3DSurface *src_surface, const RECT *rsrc, DWORD trans)
3852 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3853 IWineD3DSurfaceImpl *src = (IWineD3DSurfaceImpl *)src_surface;
3854 IWineD3DDeviceImpl *device = This->resource.device;
3856 TRACE("iface %p, dst_x %u, dst_y %u, src_surface %p, src_rect %s, flags %#x.\n",
3857 iface, dstx, dsty, src_surface, wine_dbgstr_rect(rsrc), trans);
3859 if ((This->Flags & SFLAG_LOCKED) || (src->Flags & SFLAG_LOCKED))
3861 WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3862 return WINEDDERR_SURFACEBUSY;
3865 if (device->inScene && (This == device->depth_stencil || src == device->depth_stencil))
3867 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3868 return WINED3DERR_INVALIDCALL;
3871 /* Special cases for RenderTargets */
3872 if ((This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3873 || (src->resource.usage & WINED3DUSAGE_RENDERTARGET))
3876 RECT SrcRect, DstRect;
3879 surface_get_rect(src, rsrc, &SrcRect);
3881 DstRect.left = dstx;
3883 DstRect.right = dstx + SrcRect.right - SrcRect.left;
3884 DstRect.bottom = dsty + SrcRect.bottom - SrcRect.top;
3886 /* Convert BltFast flags into Btl ones because it is called from SurfaceImpl_Blt as well */
3887 if(trans & WINEDDBLTFAST_SRCCOLORKEY)
3888 Flags |= WINEDDBLT_KEYSRC;
3889 if(trans & WINEDDBLTFAST_DESTCOLORKEY)
3890 Flags |= WINEDDBLT_KEYDEST;
3891 if(trans & WINEDDBLTFAST_WAIT)
3892 Flags |= WINEDDBLT_WAIT;
3893 if(trans & WINEDDBLTFAST_DONOTWAIT)
3894 Flags |= WINEDDBLT_DONOTWAIT;
3896 if (SUCCEEDED(IWineD3DSurfaceImpl_BltOverride(This,
3897 &DstRect, src, &SrcRect, Flags, NULL, WINED3DTEXF_POINT)))
3901 return IWineD3DBaseSurfaceImpl_BltFast(iface, dstx, dsty, src_surface, rsrc, trans);
3904 static HRESULT WINAPI IWineD3DSurfaceImpl_RealizePalette(IWineD3DSurface *iface)
3906 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3908 IWineD3DPaletteImpl *pal = This->palette;
3910 TRACE("(%p)\n", This);
3912 if (!pal) return WINED3D_OK;
3914 if (This->resource.format->id == WINED3DFMT_P8_UINT
3915 || This->resource.format->id == WINED3DFMT_P8_UINT_A8_UNORM)
3917 if (This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3919 /* Make sure the texture is up to date. This call doesn't do
3920 * anything if the texture is already up to date. */
3921 surface_load_location(This, SFLAG_INTEXTURE, NULL);
3923 /* We want to force a palette refresh, so mark the drawable as not being up to date */
3924 surface_modify_location(This, SFLAG_INDRAWABLE, FALSE);
3928 if (!(This->Flags & SFLAG_INSYSMEM))
3930 TRACE("Palette changed with surface that does not have an up to date system memory copy.\n");
3931 surface_load_location(This, SFLAG_INSYSMEM, NULL);
3933 TRACE("Dirtifying surface\n");
3934 surface_modify_location(This, SFLAG_INSYSMEM, TRUE);
3938 if(This->Flags & SFLAG_DIBSECTION) {
3939 TRACE("(%p): Updating the hdc's palette\n", This);
3940 for (n=0; n<256; n++) {
3941 col[n].rgbRed = pal->palents[n].peRed;
3942 col[n].rgbGreen = pal->palents[n].peGreen;
3943 col[n].rgbBlue = pal->palents[n].peBlue;
3944 col[n].rgbReserved = 0;
3946 SetDIBColorTable(This->hDC, 0, 256, col);
3949 /* Propagate the changes to the drawable when we have a palette. */
3950 if (This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3951 surface_load_location(This, SFLAG_INDRAWABLE, NULL);
3956 static HRESULT WINAPI IWineD3DSurfaceImpl_PrivateSetup(IWineD3DSurface *iface) {
3957 /** Check against the maximum texture sizes supported by the video card **/
3958 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3959 const struct wined3d_gl_info *gl_info = &This->resource.device->adapter->gl_info;
3960 unsigned int pow2Width, pow2Height;
3962 This->texture_name = 0;
3963 This->texture_target = GL_TEXTURE_2D;
3965 /* Non-power2 support */
3966 if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] || gl_info->supported[WINED3D_GL_NORMALIZED_TEXRECT])
3968 pow2Width = This->currentDesc.Width;
3969 pow2Height = This->currentDesc.Height;
3973 /* Find the nearest pow2 match */
3974 pow2Width = pow2Height = 1;
3975 while (pow2Width < This->currentDesc.Width) pow2Width <<= 1;
3976 while (pow2Height < This->currentDesc.Height) pow2Height <<= 1;
3978 This->pow2Width = pow2Width;
3979 This->pow2Height = pow2Height;
3981 if (pow2Width > This->currentDesc.Width || pow2Height > This->currentDesc.Height)
3983 /* TODO: Add support for non power two compressed textures. */
3984 if (This->resource.format->Flags & WINED3DFMT_FLAG_COMPRESSED)
3986 FIXME("(%p) Compressed non-power-two textures are not supported w(%d) h(%d)\n",
3987 This, This->currentDesc.Width, This->currentDesc.Height);
3988 return WINED3DERR_NOTAVAILABLE;
3992 if(pow2Width != This->currentDesc.Width ||
3993 pow2Height != This->currentDesc.Height) {
3994 This->Flags |= SFLAG_NONPOW2;
3997 TRACE("%p\n", This);
3998 if ((This->pow2Width > gl_info->limits.texture_size || This->pow2Height > gl_info->limits.texture_size)
3999 && !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL)))
4001 /* one of three options
4002 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)
4003 2: Set the texture to the maximum size (bad idea)
4004 3: WARN and return WINED3DERR_NOTAVAILABLE;
4005 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.
4007 if(This->resource.pool == WINED3DPOOL_DEFAULT || This->resource.pool == WINED3DPOOL_MANAGED)
4009 WARN("(%p) Unable to allocate a surface which exceeds the maximum OpenGL texture size\n", This);
4010 return WINED3DERR_NOTAVAILABLE;
4013 /* We should never use this surface in combination with OpenGL! */
4014 TRACE("(%p) Creating an oversized surface: %ux%u\n", This, This->pow2Width, This->pow2Height);
4018 /* Don't use ARB_TEXTURE_RECTANGLE in case the surface format is P8 and EXT_PALETTED_TEXTURE
4019 is used in combination with texture uploads (RTL_READTEX/RTL_TEXTEX). The reason is that EXT_PALETTED_TEXTURE
4020 doesn't work in combination with ARB_TEXTURE_RECTANGLE.
4022 if (This->Flags & SFLAG_NONPOW2 && gl_info->supported[ARB_TEXTURE_RECTANGLE]
4023 && !(This->resource.format->id == WINED3DFMT_P8_UINT
4024 && gl_info->supported[EXT_PALETTED_TEXTURE]
4025 && wined3d_settings.rendertargetlock_mode == RTL_READTEX))
4027 This->texture_target = GL_TEXTURE_RECTANGLE_ARB;
4028 This->pow2Width = This->currentDesc.Width;
4029 This->pow2Height = This->currentDesc.Height;
4030 This->Flags &= ~(SFLAG_NONPOW2 | SFLAG_NORMCOORD);
4034 switch (wined3d_settings.offscreen_rendering_mode)
4037 This->get_drawable_size = get_drawable_size_fbo;
4040 case ORM_BACKBUFFER:
4041 This->get_drawable_size = get_drawable_size_backbuffer;
4045 ERR("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
4046 return WINED3DERR_INVALIDCALL;
4049 This->Flags |= SFLAG_INSYSMEM;
4054 /* GL locking is done by the caller */
4055 static void surface_depth_blt(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
4056 GLuint texture, GLsizei w, GLsizei h, GLenum target)
4058 IWineD3DDeviceImpl *device = This->resource.device;
4059 GLint compare_mode = GL_NONE;
4060 struct blt_info info;
4061 GLint old_binding = 0;
4064 glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_VIEWPORT_BIT);
4066 glDisable(GL_CULL_FACE);
4067 glDisable(GL_BLEND);
4068 glDisable(GL_ALPHA_TEST);
4069 glDisable(GL_SCISSOR_TEST);
4070 glDisable(GL_STENCIL_TEST);
4071 glEnable(GL_DEPTH_TEST);
4072 glDepthFunc(GL_ALWAYS);
4073 glDepthMask(GL_TRUE);
4074 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
4075 glViewport(0, 0, w, h);
4077 SetRect(&rect, 0, h, w, 0);
4078 surface_get_blt_info(target, &rect, w, h, &info);
4079 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
4080 glGetIntegerv(info.binding, &old_binding);
4081 glBindTexture(info.bind_target, texture);
4082 if (gl_info->supported[ARB_SHADOW])
4084 glGetTexParameteriv(info.bind_target, GL_TEXTURE_COMPARE_MODE_ARB, &compare_mode);
4085 if (compare_mode != GL_NONE) glTexParameteri(info.bind_target, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE);
4088 device->shader_backend->shader_select_depth_blt((IWineD3DDevice *)device,
4089 info.tex_type, &This->ds_current_size);
4091 glBegin(GL_TRIANGLE_STRIP);
4092 glTexCoord3fv(info.coords[0]);
4093 glVertex2f(-1.0f, -1.0f);
4094 glTexCoord3fv(info.coords[1]);
4095 glVertex2f(1.0f, -1.0f);
4096 glTexCoord3fv(info.coords[2]);
4097 glVertex2f(-1.0f, 1.0f);
4098 glTexCoord3fv(info.coords[3]);
4099 glVertex2f(1.0f, 1.0f);
4102 if (compare_mode != GL_NONE) glTexParameteri(info.bind_target, GL_TEXTURE_COMPARE_MODE_ARB, compare_mode);
4103 glBindTexture(info.bind_target, old_binding);
4107 device->shader_backend->shader_deselect_depth_blt((IWineD3DDevice *)device);
4110 void surface_modify_ds_location(IWineD3DSurfaceImpl *surface,
4111 DWORD location, UINT w, UINT h)
4113 TRACE("surface %p, new location %#x, w %u, h %u.\n", surface, location, w, h);
4115 if (location & ~SFLAG_DS_LOCATIONS)
4116 FIXME("Invalid location (%#x) specified.\n", location);
4118 surface->ds_current_size.cx = w;
4119 surface->ds_current_size.cy = h;
4120 surface->Flags &= ~SFLAG_DS_LOCATIONS;
4121 surface->Flags |= location;
4124 /* Context activation is done by the caller. */
4125 void surface_load_ds_location(IWineD3DSurfaceImpl *surface, struct wined3d_context *context, DWORD location)
4127 IWineD3DDeviceImpl *device = surface->resource.device;
4128 const struct wined3d_gl_info *gl_info = context->gl_info;
4130 TRACE("surface %p, new location %#x.\n", surface, location);
4132 /* TODO: Make this work for modes other than FBO */
4133 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return;
4135 if (!(surface->Flags & location))
4137 surface->ds_current_size.cx = 0;
4138 surface->ds_current_size.cy = 0;
4141 if (surface->ds_current_size.cx == surface->currentDesc.Width
4142 && surface->ds_current_size.cy == surface->currentDesc.Height)
4144 TRACE("Location (%#x) is already up to date.\n", location);
4148 if (surface->current_renderbuffer)
4150 FIXME("Not supported with fixed up depth stencil.\n");
4154 if (!(surface->Flags & SFLAG_LOCATIONS))
4156 FIXME("No up to date depth stencil location.\n");
4157 surface->Flags |= location;
4161 if (location == SFLAG_DS_OFFSCREEN)
4163 GLint old_binding = 0;
4167 /* The render target is allowed to be smaller than the depth/stencil
4168 * buffer, so the onscreen depth/stencil buffer is potentially smaller
4169 * than the offscreen surface. Don't overwrite the offscreen surface
4170 * with undefined data. */
4171 w = min(surface->currentDesc.Width, context->swapchain->presentParms.BackBufferWidth);
4172 h = min(surface->currentDesc.Height, context->swapchain->presentParms.BackBufferHeight);
4174 TRACE("Copying onscreen depth buffer to depth texture.\n");
4178 if (!device->depth_blt_texture)
4180 glGenTextures(1, &device->depth_blt_texture);
4183 /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
4184 * directly on the FBO texture. That's because we need to flip. */
4185 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4186 if (surface->texture_target == GL_TEXTURE_RECTANGLE_ARB)
4188 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
4189 bind_target = GL_TEXTURE_RECTANGLE_ARB;
4193 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
4194 bind_target = GL_TEXTURE_2D;
4196 glBindTexture(bind_target, device->depth_blt_texture);
4197 glCopyTexImage2D(bind_target, surface->texture_level, surface->resource.format->glInternal, 0, 0, w, h, 0);
4198 glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4199 glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4200 glTexParameteri(bind_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
4201 glTexParameteri(bind_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
4202 glTexParameteri(bind_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
4203 glTexParameteri(bind_target, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
4204 glBindTexture(bind_target, old_binding);
4206 /* Setup the destination */
4207 if (!device->depth_blt_rb)
4209 gl_info->fbo_ops.glGenRenderbuffers(1, &device->depth_blt_rb);
4210 checkGLcall("glGenRenderbuffersEXT");
4212 if (device->depth_blt_rb_w != w || device->depth_blt_rb_h != h)
4214 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, device->depth_blt_rb);
4215 checkGLcall("glBindRenderbufferEXT");
4216 gl_info->fbo_ops.glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, w, h);
4217 checkGLcall("glRenderbufferStorageEXT");
4218 device->depth_blt_rb_w = w;
4219 device->depth_blt_rb_h = h;
4222 context_bind_fbo(context, GL_FRAMEBUFFER, &context->dst_fbo);
4223 gl_info->fbo_ops.glFramebufferRenderbuffer(GL_FRAMEBUFFER,
4224 GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, device->depth_blt_rb);
4225 checkGLcall("glFramebufferRenderbufferEXT");
4226 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, surface, FALSE);
4228 /* Do the actual blit */
4229 surface_depth_blt(surface, gl_info, device->depth_blt_texture, w, h, bind_target);
4230 checkGLcall("depth_blt");
4232 if (context->current_fbo) context_bind_fbo(context, GL_FRAMEBUFFER, &context->current_fbo->id);
4233 else context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4237 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
4239 else if (location == SFLAG_DS_ONSCREEN)
4241 TRACE("Copying depth texture to onscreen depth buffer.\n");
4245 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4246 surface_depth_blt(surface, gl_info, surface->texture_name,
4247 surface->currentDesc.Width, surface->currentDesc.Height, surface->texture_target);
4248 checkGLcall("depth_blt");
4250 if (context->current_fbo) context_bind_fbo(context, GL_FRAMEBUFFER, &context->current_fbo->id);
4254 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
4258 ERR("Invalid location (%#x) specified.\n", location);
4261 surface->Flags |= location;
4262 surface->ds_current_size.cx = surface->currentDesc.Width;
4263 surface->ds_current_size.cy = surface->currentDesc.Height;
4266 void surface_modify_location(IWineD3DSurfaceImpl *surface, DWORD flag, BOOL persistent)
4268 IWineD3DSurfaceImpl *overlay;
4270 TRACE("surface %p, location %s, persistent %#x.\n",
4271 surface, debug_surflocation(flag), persistent);
4273 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
4275 if (surface_is_offscreen(surface))
4277 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4278 if (flag & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE)) flag |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4282 TRACE("Surface %p is an onscreen surface.\n", surface);
4288 if (((surface->Flags & SFLAG_INTEXTURE) && !(flag & SFLAG_INTEXTURE))
4289 || ((surface->Flags & SFLAG_INSRGBTEX) && !(flag & SFLAG_INSRGBTEX)))
4291 if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
4293 TRACE("Passing to container.\n");
4294 IWineD3DBaseTexture_SetDirty((IWineD3DBaseTexture *)surface->container.u.texture, TRUE);
4297 surface->Flags &= ~SFLAG_LOCATIONS;
4298 surface->Flags |= flag;
4300 /* Redraw emulated overlays, if any */
4301 if (flag & SFLAG_INDRAWABLE && !list_empty(&surface->overlays))
4303 LIST_FOR_EACH_ENTRY(overlay, &surface->overlays, IWineD3DSurfaceImpl, overlay_entry)
4305 IWineD3DSurface_DrawOverlay((IWineD3DSurface *)overlay);
4311 if ((surface->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) && (flag & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)))
4313 if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
4315 TRACE("Passing to container\n");
4316 IWineD3DBaseTexture_SetDirty((IWineD3DBaseTexture *)surface->container.u.texture, TRUE);
4319 surface->Flags &= ~flag;
4322 if (!(surface->Flags & SFLAG_LOCATIONS))
4324 ERR("Surface %p does not have any up to date location.\n", surface);
4328 static inline void surface_blt_to_drawable(IWineD3DSurfaceImpl *This, const RECT *rect_in)
4330 IWineD3DDeviceImpl *device = This->resource.device;
4331 IWineD3DSwapChainImpl *swapchain;
4332 struct wined3d_context *context;
4333 RECT src_rect, dst_rect;
4335 surface_get_rect(This, rect_in, &src_rect);
4337 context = context_acquire(device, This);
4338 context_apply_blit_state(context, device);
4340 dst_rect = src_rect;
4341 if (context->render_offscreen)
4343 dst_rect.top = This->currentDesc.Height - dst_rect.top;
4344 dst_rect.bottom = This->currentDesc.Height - dst_rect.bottom;
4347 swapchain = This->container.type == WINED3D_CONTAINER_SWAPCHAIN ? This->container.u.swapchain : NULL;
4348 if (swapchain && This == swapchain->front_buffer)
4349 surface_translate_frontbuffer_coords(This, context->win_handle, &dst_rect);
4351 device->blitter->set_shader((IWineD3DDevice *) device, This);
4354 draw_textured_quad(This, &src_rect, &dst_rect, WINED3DTEXF_POINT);
4357 device->blitter->unset_shader((IWineD3DDevice *) device);
4359 if (wined3d_settings.strict_draw_ordering || (swapchain
4360 && (This == swapchain->front_buffer || swapchain->num_contexts > 1)))
4361 wglFlush(); /* Flush to ensure ordering across contexts. */
4363 context_release(context);
4366 HRESULT surface_load_location(IWineD3DSurfaceImpl *surface, DWORD flag, const RECT *rect)
4368 IWineD3DDeviceImpl *device = surface->resource.device;
4369 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4370 BOOL drawable_read_ok = surface_is_offscreen(surface);
4371 struct wined3d_format format;
4372 CONVERT_TYPES convert;
4373 int width, pitch, outpitch;
4375 BOOL in_fbo = FALSE;
4377 TRACE("surface %p, location %s, rect %s.\n", surface, debug_surflocation(flag), wine_dbgstr_rect(rect));
4379 if (surface->resource.usage & WINED3DUSAGE_DEPTHSTENCIL)
4381 if (flag == SFLAG_INTEXTURE)
4383 struct wined3d_context *context = context_acquire(device, NULL);
4384 surface_load_ds_location(surface, context, SFLAG_DS_OFFSCREEN);
4385 context_release(context);
4390 FIXME("Unimplemented location %s for depth/stencil buffers.\n", debug_surflocation(flag));
4391 return WINED3DERR_INVALIDCALL;
4395 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
4397 if (surface_is_offscreen(surface))
4399 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets.
4400 * Prefer SFLAG_INTEXTURE. */
4401 if (flag == SFLAG_INDRAWABLE) flag = SFLAG_INTEXTURE;
4402 drawable_read_ok = FALSE;
4407 TRACE("Surface %p is an onscreen surface.\n", surface);
4411 if (surface->Flags & flag)
4413 TRACE("Location already up to date\n");
4417 if (!(surface->Flags & SFLAG_LOCATIONS))
4419 ERR("Surface %p does not have any up to date location.\n", surface);
4420 surface->Flags |= SFLAG_LOST;
4421 return WINED3DERR_DEVICELOST;
4424 if (flag == SFLAG_INSYSMEM)
4426 surface_prepare_system_memory(surface);
4428 /* Download the surface to system memory */
4429 if (surface->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX))
4431 struct wined3d_context *context = NULL;
4433 if (!device->isInDraw) context = context_acquire(device, NULL);
4435 surface_bind_and_dirtify(surface, !(surface->Flags & SFLAG_INTEXTURE));
4436 surface_download_data(surface, gl_info);
4438 if (context) context_release(context);
4442 /* Note: It might be faster to download into a texture first. */
4443 read_from_framebuffer(surface, rect, surface->resource.allocatedMemory,
4444 IWineD3DSurface_GetPitch((IWineD3DSurface *)surface));
4447 else if (flag == SFLAG_INDRAWABLE)
4449 if (surface->Flags & SFLAG_INTEXTURE)
4451 surface_blt_to_drawable(surface, rect);
4456 if ((surface->Flags & SFLAG_LOCATIONS) == SFLAG_INSRGBTEX)
4458 /* This needs a shader to convert the srgb data sampled from the GL texture into RGB
4459 * values, otherwise we get incorrect values in the target. For now go the slow way
4460 * via a system memory copy
4462 surface_load_location(surface, SFLAG_INSYSMEM, rect);
4465 d3dfmt_get_conv(surface, FALSE /* We need color keying */,
4466 FALSE /* We won't use textures */, &format, &convert);
4468 /* The width is in 'length' not in bytes */
4469 width = surface->currentDesc.Width;
4470 pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *)surface);
4472 /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4473 * but it isn't set (yet) in all cases it is getting called. */
4474 if ((convert != NO_CONVERSION) && (surface->Flags & SFLAG_PBO))
4476 struct wined3d_context *context = NULL;
4478 TRACE("Removing the pbo attached to surface %p.\n", surface);
4480 if (!device->isInDraw) context = context_acquire(device, NULL);
4481 surface_remove_pbo(surface, gl_info);
4482 if (context) context_release(context);
4485 if ((convert != NO_CONVERSION) && surface->resource.allocatedMemory)
4487 int height = surface->currentDesc.Height;
4488 byte_count = format.conv_byte_count;
4490 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4491 outpitch = width * byte_count;
4492 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4494 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4496 ERR("Out of memory %d, %d!\n", outpitch, height);
4497 return WINED3DERR_OUTOFVIDEOMEMORY;
4499 d3dfmt_convert_surface(surface->resource.allocatedMemory, mem, pitch,
4500 width, height, outpitch, convert, surface);
4502 surface->Flags |= SFLAG_CONVERTED;
4506 surface->Flags &= ~SFLAG_CONVERTED;
4507 mem = surface->resource.allocatedMemory;
4508 byte_count = format.byte_count;
4511 flush_to_framebuffer_drawpixels(surface, format.glFormat, format.glType, byte_count, mem);
4513 /* Don't delete PBO memory */
4514 if ((mem != surface->resource.allocatedMemory) && !(surface->Flags & SFLAG_PBO))
4515 HeapFree(GetProcessHeap(), 0, mem);
4518 else /* if(flag & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) */
4520 const DWORD attach_flags = WINED3DFMT_FLAG_FBO_ATTACHABLE | WINED3DFMT_FLAG_FBO_ATTACHABLE_SRGB;
4522 if (drawable_read_ok && (surface->Flags & SFLAG_INDRAWABLE))
4524 read_from_framebuffer_texture(surface, flag == SFLAG_INSRGBTEX);
4526 else if (surface->Flags & (SFLAG_INSRGBTEX | SFLAG_INTEXTURE)
4527 && (surface->resource.format->Flags & attach_flags) == attach_flags
4528 && fbo_blit_supported(gl_info, BLIT_OP_BLIT,
4529 NULL, surface->resource.usage, surface->resource.pool, surface->resource.format,
4530 NULL, surface->resource.usage, surface->resource.pool, surface->resource.format))
4532 DWORD src_location = flag == SFLAG_INSRGBTEX ? SFLAG_INTEXTURE : SFLAG_INSRGBTEX;
4533 RECT rect = {0, 0, surface->currentDesc.Width, surface->currentDesc.Height};
4535 surface_blt_fbo(surface->resource.device, WINED3DTEXF_POINT,
4536 surface, src_location, &rect, surface, flag, &rect);
4540 /* Upload from system memory */
4541 BOOL srgb = flag == SFLAG_INSRGBTEX;
4542 struct wined3d_context *context = NULL;
4544 d3dfmt_get_conv(surface, TRUE /* We need color keying */,
4545 TRUE /* We will use textures */, &format, &convert);
4549 if ((surface->Flags & (SFLAG_INTEXTURE | SFLAG_INSYSMEM)) == SFLAG_INTEXTURE)
4551 /* Performance warning... */
4552 FIXME("Downloading RGB surface %p to reload it as sRGB.\n", surface);
4553 surface_load_location(surface, SFLAG_INSYSMEM, rect);
4558 if ((surface->Flags & (SFLAG_INSRGBTEX | SFLAG_INSYSMEM)) == SFLAG_INSRGBTEX)
4560 /* Performance warning... */
4561 FIXME("Downloading sRGB surface %p to reload it as RGB.\n", surface);
4562 surface_load_location(surface, SFLAG_INSYSMEM, rect);
4565 if (!(surface->Flags & SFLAG_INSYSMEM))
4567 WARN("Trying to load a texture from sysmem, but SFLAG_INSYSMEM is not set.\n");
4568 /* Lets hope we get it from somewhere... */
4569 surface_load_location(surface, SFLAG_INSYSMEM, rect);
4572 if (!device->isInDraw) context = context_acquire(device, NULL);
4574 surface_prepare_texture(surface, gl_info, srgb);
4575 surface_bind_and_dirtify(surface, srgb);
4577 if (surface->CKeyFlags & WINEDDSD_CKSRCBLT)
4579 surface->Flags |= SFLAG_GLCKEY;
4580 surface->glCKey = surface->SrcBltCKey;
4582 else surface->Flags &= ~SFLAG_GLCKEY;
4584 /* The width is in 'length' not in bytes */
4585 width = surface->currentDesc.Width;
4586 pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *)surface);
4588 /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4589 * but it isn't set (yet) in all cases it is getting called. */
4590 if ((convert != NO_CONVERSION || format.convert) && (surface->Flags & SFLAG_PBO))
4592 TRACE("Removing the pbo attached to surface %p.\n", surface);
4593 surface_remove_pbo(surface, gl_info);
4598 /* This code is entered for texture formats which need a fixup. */
4599 int height = surface->currentDesc.Height;
4601 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4602 outpitch = width * format.conv_byte_count;
4603 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4605 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4607 ERR("Out of memory %d, %d!\n", outpitch, height);
4608 if (context) context_release(context);
4609 return WINED3DERR_OUTOFVIDEOMEMORY;
4611 format.convert(surface->resource.allocatedMemory, mem, pitch, width, height);
4613 else if (convert != NO_CONVERSION && surface->resource.allocatedMemory)
4615 /* This code is only entered for color keying fixups */
4616 int height = surface->currentDesc.Height;
4618 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4619 outpitch = width * format.conv_byte_count;
4620 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4622 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4624 ERR("Out of memory %d, %d!\n", outpitch, height);
4625 if (context) context_release(context);
4626 return WINED3DERR_OUTOFVIDEOMEMORY;
4628 d3dfmt_convert_surface(surface->resource.allocatedMemory, mem, pitch,
4629 width, height, outpitch, convert, surface);
4633 mem = surface->resource.allocatedMemory;
4636 /* Make sure the correct pitch is used */
4638 glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
4641 if (mem || (surface->Flags & SFLAG_PBO))
4642 surface_upload_data(surface, gl_info, &format, srgb, mem);
4644 /* Restore the default pitch */
4646 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
4649 if (context) context_release(context);
4651 /* Don't delete PBO memory */
4652 if ((mem != surface->resource.allocatedMemory) && !(surface->Flags & SFLAG_PBO))
4653 HeapFree(GetProcessHeap(), 0, mem);
4657 if (!rect) surface->Flags |= flag;
4659 if (in_fbo && (surface->Flags & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE)))
4661 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4662 surface->Flags |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4668 static WINED3DSURFTYPE WINAPI IWineD3DSurfaceImpl_GetImplType(IWineD3DSurface *iface) {
4669 return SURFACE_OPENGL;
4672 static HRESULT WINAPI IWineD3DSurfaceImpl_DrawOverlay(IWineD3DSurface *iface) {
4673 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4676 /* If there's no destination surface there is nothing to do */
4677 if(!This->overlay_dest) return WINED3D_OK;
4679 /* Blt calls ModifyLocation on the dest surface, which in turn calls DrawOverlay to
4680 * update the overlay. Prevent an endless recursion
4682 if(This->overlay_dest->Flags & SFLAG_INOVERLAYDRAW) {
4685 This->overlay_dest->Flags |= SFLAG_INOVERLAYDRAW;
4686 hr = IWineD3DSurfaceImpl_Blt((IWineD3DSurface *) This->overlay_dest, &This->overlay_destrect,
4687 iface, &This->overlay_srcrect, WINEDDBLT_WAIT,
4688 NULL, WINED3DTEXF_LINEAR);
4689 This->overlay_dest->Flags &= ~SFLAG_INOVERLAYDRAW;
4694 BOOL surface_is_offscreen(IWineD3DSurfaceImpl *surface)
4696 IWineD3DSwapChainImpl *swapchain = surface->container.u.swapchain;
4698 /* Not on a swapchain - must be offscreen */
4699 if (surface->container.type != WINED3D_CONTAINER_SWAPCHAIN) return TRUE;
4701 /* The front buffer is always onscreen */
4702 if (surface == swapchain->front_buffer) return FALSE;
4704 /* If the swapchain is rendered to an FBO, the backbuffer is
4705 * offscreen, otherwise onscreen */
4706 return swapchain->render_to_fbo;
4709 const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl =
4712 IWineD3DBaseSurfaceImpl_QueryInterface,
4713 IWineD3DBaseSurfaceImpl_AddRef,
4714 IWineD3DSurfaceImpl_Release,
4715 /* IWineD3DResource */
4716 IWineD3DBaseSurfaceImpl_GetParent,
4717 IWineD3DBaseSurfaceImpl_SetPrivateData,
4718 IWineD3DBaseSurfaceImpl_GetPrivateData,
4719 IWineD3DBaseSurfaceImpl_FreePrivateData,
4720 IWineD3DBaseSurfaceImpl_SetPriority,
4721 IWineD3DBaseSurfaceImpl_GetPriority,
4722 IWineD3DSurfaceImpl_PreLoad,
4723 IWineD3DSurfaceImpl_UnLoad,
4724 IWineD3DBaseSurfaceImpl_GetType,
4725 /* IWineD3DSurface */
4726 IWineD3DBaseSurfaceImpl_GetDesc,
4727 IWineD3DSurfaceImpl_Map,
4728 IWineD3DSurfaceImpl_Unmap,
4729 IWineD3DSurfaceImpl_GetDC,
4730 IWineD3DSurfaceImpl_ReleaseDC,
4731 IWineD3DSurfaceImpl_Flip,
4732 IWineD3DSurfaceImpl_Blt,
4733 IWineD3DBaseSurfaceImpl_GetBltStatus,
4734 IWineD3DBaseSurfaceImpl_GetFlipStatus,
4735 IWineD3DBaseSurfaceImpl_IsLost,
4736 IWineD3DBaseSurfaceImpl_Restore,
4737 IWineD3DSurfaceImpl_BltFast,
4738 IWineD3DBaseSurfaceImpl_GetPalette,
4739 IWineD3DBaseSurfaceImpl_SetPalette,
4740 IWineD3DSurfaceImpl_RealizePalette,
4741 IWineD3DBaseSurfaceImpl_SetColorKey,
4742 IWineD3DBaseSurfaceImpl_GetPitch,
4743 IWineD3DSurfaceImpl_SetMem,
4744 IWineD3DBaseSurfaceImpl_SetOverlayPosition,
4745 IWineD3DBaseSurfaceImpl_GetOverlayPosition,
4746 IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder,
4747 IWineD3DBaseSurfaceImpl_UpdateOverlay,
4748 IWineD3DBaseSurfaceImpl_SetClipper,
4749 IWineD3DBaseSurfaceImpl_GetClipper,
4751 IWineD3DSurfaceImpl_LoadTexture,
4752 IWineD3DSurfaceImpl_BindTexture,
4753 IWineD3DBaseSurfaceImpl_GetData,
4754 IWineD3DSurfaceImpl_SetFormat,
4755 IWineD3DSurfaceImpl_PrivateSetup,
4756 IWineD3DSurfaceImpl_GetImplType,
4757 IWineD3DSurfaceImpl_DrawOverlay
4760 static HRESULT ffp_blit_alloc(IWineD3DDevice *iface) { return WINED3D_OK; }
4761 /* Context activation is done by the caller. */
4762 static void ffp_blit_free(IWineD3DDevice *iface) { }
4764 /* This function is used in case of 8bit paletted textures using GL_EXT_paletted_texture */
4765 /* Context activation is done by the caller. */
4766 static void ffp_blit_p8_upload_palette(IWineD3DSurfaceImpl *surface, const struct wined3d_gl_info *gl_info)
4769 BOOL colorkey_active = (surface->CKeyFlags & WINEDDSD_CKSRCBLT) ? TRUE : FALSE;
4771 d3dfmt_p8_init_palette(surface, table, colorkey_active);
4773 TRACE("Using GL_EXT_PALETTED_TEXTURE for 8-bit paletted texture support\n");
4775 GL_EXTCALL(glColorTableEXT(surface->texture_target, GL_RGBA, 256, GL_RGBA, GL_UNSIGNED_BYTE, table));
4779 /* Context activation is done by the caller. */
4780 static HRESULT ffp_blit_set(IWineD3DDevice *iface, IWineD3DSurfaceImpl *surface)
4782 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
4783 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4784 enum complex_fixup fixup = get_complex_fixup(surface->resource.format->color_fixup);
4786 /* When EXT_PALETTED_TEXTURE is around, palette conversion is done by the GPU
4787 * else the surface is converted in software at upload time in LoadLocation.
4789 if(fixup == COMPLEX_FIXUP_P8 && gl_info->supported[EXT_PALETTED_TEXTURE])
4790 ffp_blit_p8_upload_palette(surface, gl_info);
4793 glEnable(surface->texture_target);
4794 checkGLcall("glEnable(surface->texture_target)");
4799 /* Context activation is done by the caller. */
4800 static void ffp_blit_unset(IWineD3DDevice *iface)
4802 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
4803 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4806 glDisable(GL_TEXTURE_2D);
4807 checkGLcall("glDisable(GL_TEXTURE_2D)");
4808 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
4810 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
4811 checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
4813 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4815 glDisable(GL_TEXTURE_RECTANGLE_ARB);
4816 checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
4821 static BOOL ffp_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4822 const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool, const struct wined3d_format *src_format,
4823 const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool, const struct wined3d_format *dst_format)
4825 enum complex_fixup src_fixup;
4827 if (blit_op == BLIT_OP_COLOR_FILL)
4829 if (!(dst_usage & WINED3DUSAGE_RENDERTARGET))
4831 TRACE("Color fill not supported\n");
4838 src_fixup = get_complex_fixup(src_format->color_fixup);
4839 if (TRACE_ON(d3d_surface) && TRACE_ON(d3d))
4841 TRACE("Checking support for fixup:\n");
4842 dump_color_fixup_desc(src_format->color_fixup);
4845 if (blit_op != BLIT_OP_BLIT)
4847 TRACE("Unsupported blit_op=%d\n", blit_op);
4851 if (!is_identity_fixup(dst_format->color_fixup))
4853 TRACE("Destination fixups are not supported\n");
4857 if (src_fixup == COMPLEX_FIXUP_P8 && gl_info->supported[EXT_PALETTED_TEXTURE])
4859 TRACE("P8 fixup supported\n");
4863 /* We only support identity conversions. */
4864 if (is_identity_fixup(src_format->color_fixup))
4870 TRACE("[FAILED]\n");
4874 /* Do not call while under the GL lock. */
4875 static HRESULT ffp_blit_color_fill(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *dst_surface,
4876 const RECT *dst_rect, const WINED3DCOLORVALUE *color)
4878 const RECT draw_rect = {0, 0, dst_surface->currentDesc.Width, dst_surface->currentDesc.Height};
4880 return device_clear_render_targets(device, 1 /* rt_count */, &dst_surface, 1 /* rect_count */,
4881 dst_rect, &draw_rect, WINED3DCLEAR_TARGET, color, 0.0f /* depth */, 0 /* stencil */);
4884 const struct blit_shader ffp_blit = {
4893 static HRESULT cpu_blit_alloc(IWineD3DDevice *iface)
4898 /* Context activation is done by the caller. */
4899 static void cpu_blit_free(IWineD3DDevice *iface)
4903 /* Context activation is done by the caller. */
4904 static HRESULT cpu_blit_set(IWineD3DDevice *iface, IWineD3DSurfaceImpl *surface)
4909 /* Context activation is done by the caller. */
4910 static void cpu_blit_unset(IWineD3DDevice *iface)
4914 static BOOL cpu_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4915 const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool, const struct wined3d_format *src_format,
4916 const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool, const struct wined3d_format *dst_format)
4918 if (blit_op == BLIT_OP_COLOR_FILL)
4926 /* Do not call while under the GL lock. */
4927 static HRESULT cpu_blit_color_fill(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *dst_surface,
4928 const RECT *dst_rect, const WINED3DCOLORVALUE *color)
4932 memset(&BltFx, 0, sizeof(BltFx));
4933 BltFx.dwSize = sizeof(BltFx);
4934 BltFx.u5.dwFillColor = wined3d_format_convert_from_float(dst_surface->resource.format, color);
4935 return IWineD3DBaseSurfaceImpl_Blt((IWineD3DSurface*)dst_surface, dst_rect,
4936 NULL, NULL, WINEDDBLT_COLORFILL, &BltFx, WINED3DTEXF_POINT);
4939 const struct blit_shader cpu_blit = {
4948 static BOOL fbo_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4949 const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool, const struct wined3d_format *src_format,
4950 const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool, const struct wined3d_format *dst_format)
4952 if ((wined3d_settings.offscreen_rendering_mode != ORM_FBO) || !gl_info->fbo_ops.glBlitFramebuffer)
4955 /* We only support blitting. Things like color keying / color fill should
4956 * be handled by other blitters.
4958 if (blit_op != BLIT_OP_BLIT)
4961 /* Source and/or destination need to be on the GL side */
4962 if (src_pool == WINED3DPOOL_SYSTEMMEM || dst_pool == WINED3DPOOL_SYSTEMMEM)
4965 if (!((src_format->Flags & WINED3DFMT_FLAG_FBO_ATTACHABLE) || (src_usage & WINED3DUSAGE_RENDERTARGET))
4966 && ((dst_format->Flags & WINED3DFMT_FLAG_FBO_ATTACHABLE) || (dst_usage & WINED3DUSAGE_RENDERTARGET)))
4969 if (!(src_format->id == dst_format->id
4970 || (is_identity_fixup(src_format->color_fixup)
4971 && is_identity_fixup(dst_format->color_fixup))))