ddraw/tests: Add an observation regarding device color model criteria for IDirect3D3...
[wine.git] / dlls / wined3d / surface.c
blob73c5aff5f9e542274dced37ac002322fdde9a359
1 /*
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
30 #include "config.h"
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 IWineD3DDeviceImpl *device = This->resource.device;
40 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
41 struct wined3d_context *context = NULL;
42 renderbuffer_entry_t *entry, *entry2;
44 TRACE("(%p) : Cleaning up.\n", This);
46 /* Need a context to destroy the texture. Use the currently active render
47 * target, but only if the primary render target exists. Otherwise
48 * lastActiveRenderTarget is garbage. When destroying the primary render
49 * target, Uninit3D() will activate a context before doing anything. */
50 if (device->render_targets && device->render_targets[0])
52 context = context_acquire(device, NULL);
55 ENTER_GL();
57 if (This->texture_name)
59 /* Release the OpenGL texture. */
60 TRACE("Deleting texture %u.\n", This->texture_name);
61 glDeleteTextures(1, &This->texture_name);
64 if (This->Flags & SFLAG_PBO)
66 /* Delete the PBO. */
67 GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
70 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry)
72 gl_info->fbo_ops.glDeleteRenderbuffers(1, &entry->id);
73 HeapFree(GetProcessHeap(), 0, entry);
76 LEAVE_GL();
78 if (This->Flags & SFLAG_DIBSECTION)
80 /* Release the DC. */
81 SelectObject(This->hDC, This->dib.holdbitmap);
82 DeleteDC(This->hDC);
83 /* Release the DIB section. */
84 DeleteObject(This->dib.DIBsection);
85 This->dib.bitmap_data = NULL;
86 This->resource.allocatedMemory = NULL;
89 if (This->Flags & SFLAG_USERPTR) IWineD3DSurface_SetMem((IWineD3DSurface *)This, NULL);
90 if (This->overlay_dest) list_remove(&This->overlay_entry);
92 HeapFree(GetProcessHeap(), 0, This->palette9);
94 resource_cleanup((IWineD3DResource *)This);
96 if (context) context_release(context);
99 UINT surface_calculate_size(const struct wined3d_format_desc *format_desc, UINT alignment, UINT width, UINT height)
101 UINT size;
103 if (format_desc->format == WINED3DFMT_UNKNOWN)
105 size = 0;
107 else if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
109 UINT row_block_count = (width + format_desc->block_width - 1) / format_desc->block_width;
110 UINT row_count = (height + format_desc->block_height - 1) / format_desc->block_height;
111 size = row_count * row_block_count * format_desc->block_byte_count;
113 else
115 /* The pitch is a multiple of 4 bytes. */
116 size = height * (((width * format_desc->byte_count) + alignment - 1) & ~(alignment - 1));
119 if (format_desc->heightscale != 0.0f) size *= format_desc->heightscale;
121 return size;
124 struct blt_info
126 GLenum binding;
127 GLenum bind_target;
128 enum tex_types tex_type;
129 GLfloat coords[4][3];
132 struct float_rect
134 float l;
135 float t;
136 float r;
137 float b;
140 static inline void cube_coords_float(const RECT *r, UINT w, UINT h, struct float_rect *f)
142 f->l = ((r->left * 2.0f) / w) - 1.0f;
143 f->t = ((r->top * 2.0f) / h) - 1.0f;
144 f->r = ((r->right * 2.0f) / w) - 1.0f;
145 f->b = ((r->bottom * 2.0f) / h) - 1.0f;
148 static void surface_get_blt_info(GLenum target, const RECT *rect_in, GLsizei w, GLsizei h, struct blt_info *info)
150 GLfloat (*coords)[3] = info->coords;
151 RECT rect;
152 struct float_rect f;
154 if (rect_in)
155 rect = *rect_in;
156 else
158 rect.left = 0;
159 rect.top = h;
160 rect.right = w;
161 rect.bottom = 0;
164 switch (target)
166 default:
167 FIXME("Unsupported texture target %#x\n", target);
168 /* Fall back to GL_TEXTURE_2D */
169 case GL_TEXTURE_2D:
170 info->binding = GL_TEXTURE_BINDING_2D;
171 info->bind_target = GL_TEXTURE_2D;
172 info->tex_type = tex_2d;
173 coords[0][0] = (float)rect.left / w;
174 coords[0][1] = (float)rect.top / h;
175 coords[0][2] = 0.0f;
177 coords[1][0] = (float)rect.right / w;
178 coords[1][1] = (float)rect.top / h;
179 coords[1][2] = 0.0f;
181 coords[2][0] = (float)rect.left / w;
182 coords[2][1] = (float)rect.bottom / h;
183 coords[2][2] = 0.0f;
185 coords[3][0] = (float)rect.right / w;
186 coords[3][1] = (float)rect.bottom / h;
187 coords[3][2] = 0.0f;
188 break;
190 case GL_TEXTURE_RECTANGLE_ARB:
191 info->binding = GL_TEXTURE_BINDING_RECTANGLE_ARB;
192 info->bind_target = GL_TEXTURE_RECTANGLE_ARB;
193 info->tex_type = tex_rect;
194 coords[0][0] = rect.left; coords[0][1] = rect.top; coords[0][2] = 0.0f;
195 coords[1][0] = rect.right; coords[1][1] = rect.top; coords[1][2] = 0.0f;
196 coords[2][0] = rect.left; coords[2][1] = rect.bottom; coords[2][2] = 0.0f;
197 coords[3][0] = rect.right; coords[3][1] = rect.bottom; coords[3][2] = 0.0f;
198 break;
200 case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
201 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
202 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
203 info->tex_type = tex_cube;
204 cube_coords_float(&rect, w, h, &f);
206 coords[0][0] = 1.0f; coords[0][1] = -f.t; coords[0][2] = -f.l;
207 coords[1][0] = 1.0f; coords[1][1] = -f.t; coords[1][2] = -f.r;
208 coords[2][0] = 1.0f; coords[2][1] = -f.b; coords[2][2] = -f.l;
209 coords[3][0] = 1.0f; coords[3][1] = -f.b; coords[3][2] = -f.r;
210 break;
212 case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
213 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
214 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
215 info->tex_type = tex_cube;
216 cube_coords_float(&rect, w, h, &f);
218 coords[0][0] = -1.0f; coords[0][1] = -f.t; coords[0][2] = f.l;
219 coords[1][0] = -1.0f; coords[1][1] = -f.t; coords[1][2] = f.r;
220 coords[2][0] = -1.0f; coords[2][1] = -f.b; coords[2][2] = f.l;
221 coords[3][0] = -1.0f; coords[3][1] = -f.b; coords[3][2] = f.r;
222 break;
224 case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
225 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
226 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
227 info->tex_type = tex_cube;
228 cube_coords_float(&rect, w, h, &f);
230 coords[0][0] = f.l; coords[0][1] = 1.0f; coords[0][2] = f.t;
231 coords[1][0] = f.r; coords[1][1] = 1.0f; coords[1][2] = f.t;
232 coords[2][0] = f.l; coords[2][1] = 1.0f; coords[2][2] = f.b;
233 coords[3][0] = f.r; coords[3][1] = 1.0f; coords[3][2] = f.b;
234 break;
236 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
237 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
238 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
239 info->tex_type = tex_cube;
240 cube_coords_float(&rect, w, h, &f);
242 coords[0][0] = f.l; coords[0][1] = -1.0f; coords[0][2] = -f.t;
243 coords[1][0] = f.r; coords[1][1] = -1.0f; coords[1][2] = -f.t;
244 coords[2][0] = f.l; coords[2][1] = -1.0f; coords[2][2] = -f.b;
245 coords[3][0] = f.r; coords[3][1] = -1.0f; coords[3][2] = -f.b;
246 break;
248 case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
249 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
250 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
251 info->tex_type = tex_cube;
252 cube_coords_float(&rect, w, h, &f);
254 coords[0][0] = f.l; coords[0][1] = -f.t; coords[0][2] = 1.0f;
255 coords[1][0] = f.r; coords[1][1] = -f.t; coords[1][2] = 1.0f;
256 coords[2][0] = f.l; coords[2][1] = -f.b; coords[2][2] = 1.0f;
257 coords[3][0] = f.r; coords[3][1] = -f.b; coords[3][2] = 1.0f;
258 break;
260 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
261 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
262 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
263 info->tex_type = tex_cube;
264 cube_coords_float(&rect, w, h, &f);
266 coords[0][0] = -f.l; coords[0][1] = -f.t; coords[0][2] = -1.0f;
267 coords[1][0] = -f.r; coords[1][1] = -f.t; coords[1][2] = -1.0f;
268 coords[2][0] = -f.l; coords[2][1] = -f.b; coords[2][2] = -1.0f;
269 coords[3][0] = -f.r; coords[3][1] = -f.b; coords[3][2] = -1.0f;
270 break;
274 static inline void surface_get_rect(IWineD3DSurfaceImpl *This, const RECT *rect_in, RECT *rect_out)
276 if (rect_in)
277 *rect_out = *rect_in;
278 else
280 rect_out->left = 0;
281 rect_out->top = 0;
282 rect_out->right = This->currentDesc.Width;
283 rect_out->bottom = This->currentDesc.Height;
287 /* GL locking and context activation is done by the caller */
288 void draw_textured_quad(IWineD3DSurfaceImpl *src_surface, const RECT *src_rect, const RECT *dst_rect, WINED3DTEXTUREFILTERTYPE Filter)
290 IWineD3DBaseTextureImpl *texture;
291 struct blt_info info;
293 surface_get_blt_info(src_surface->texture_target, src_rect, src_surface->pow2Width, src_surface->pow2Height, &info);
295 glEnable(info.bind_target);
296 checkGLcall("glEnable(bind_target)");
298 /* Bind the texture */
299 glBindTexture(info.bind_target, src_surface->texture_name);
300 checkGLcall("glBindTexture");
302 /* Filtering for StretchRect */
303 glTexParameteri(info.bind_target, GL_TEXTURE_MAG_FILTER,
304 wined3d_gl_mag_filter(magLookup, Filter));
305 checkGLcall("glTexParameteri");
306 glTexParameteri(info.bind_target, GL_TEXTURE_MIN_FILTER,
307 wined3d_gl_min_mip_filter(minMipLookup, Filter, WINED3DTEXF_NONE));
308 checkGLcall("glTexParameteri");
309 glTexParameteri(info.bind_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
310 glTexParameteri(info.bind_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
311 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
312 checkGLcall("glTexEnvi");
314 /* Draw a quad */
315 glBegin(GL_TRIANGLE_STRIP);
316 glTexCoord3fv(info.coords[0]);
317 glVertex2i(dst_rect->left, dst_rect->top);
319 glTexCoord3fv(info.coords[1]);
320 glVertex2i(dst_rect->right, dst_rect->top);
322 glTexCoord3fv(info.coords[2]);
323 glVertex2i(dst_rect->left, dst_rect->bottom);
325 glTexCoord3fv(info.coords[3]);
326 glVertex2i(dst_rect->right, dst_rect->bottom);
327 glEnd();
329 /* Unbind the texture */
330 glBindTexture(info.bind_target, 0);
331 checkGLcall("glBindTexture(info->bind_target, 0)");
333 /* We changed the filtering settings on the texture. Inform the
334 * container about this to get the filters reset properly next draw. */
335 if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)src_surface, &IID_IWineD3DBaseTexture, (void **)&texture)))
337 texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
338 texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
339 texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
340 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture);
344 HRESULT surface_init(IWineD3DSurfaceImpl *surface, WINED3DSURFTYPE surface_type, UINT alignment,
345 UINT width, UINT height, UINT level, BOOL lockable, BOOL discard, WINED3DMULTISAMPLE_TYPE multisample_type,
346 UINT multisample_quality, IWineD3DDeviceImpl *device, DWORD usage, WINED3DFORMAT format,
347 WINED3DPOOL pool, IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
349 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
350 const struct wined3d_format_desc *format_desc = getFormatDescEntry(format, gl_info);
351 void (*cleanup)(IWineD3DSurfaceImpl *This);
352 unsigned int resource_size;
353 HRESULT hr;
355 if (multisample_quality > 0)
357 FIXME("multisample_quality set to %u, substituting 0\n", multisample_quality);
358 multisample_quality = 0;
361 /* FIXME: Check that the format is supported by the device. */
363 resource_size = surface_calculate_size(format_desc, alignment, width, height);
365 /* Look at the implementation and set the correct Vtable. */
366 switch (surface_type)
368 case SURFACE_OPENGL:
369 surface->lpVtbl = &IWineD3DSurface_Vtbl;
370 cleanup = surface_cleanup;
371 break;
373 case SURFACE_GDI:
374 surface->lpVtbl = &IWineGDISurface_Vtbl;
375 cleanup = surface_gdi_cleanup;
376 break;
378 default:
379 ERR("Requested unknown surface implementation %#x.\n", surface_type);
380 return WINED3DERR_INVALIDCALL;
383 hr = resource_init((IWineD3DResource *)surface, WINED3DRTYPE_SURFACE,
384 device, resource_size, usage, format_desc, pool, parent, parent_ops);
385 if (FAILED(hr))
387 WARN("Failed to initialize resource, returning %#x.\n", hr);
388 return hr;
391 /* "Standalone" surface. */
392 IWineD3DSurface_SetContainer((IWineD3DSurface *)surface, NULL);
394 surface->currentDesc.Width = width;
395 surface->currentDesc.Height = height;
396 surface->currentDesc.MultiSampleType = multisample_type;
397 surface->currentDesc.MultiSampleQuality = multisample_quality;
398 surface->texture_level = level;
399 list_init(&surface->overlays);
401 /* Flags */
402 surface->Flags = SFLAG_NORMCOORD; /* Default to normalized coords. */
403 if (discard) surface->Flags |= SFLAG_DISCARD;
404 if (lockable || format == WINED3DFMT_D16_LOCKABLE) surface->Flags |= SFLAG_LOCKABLE;
406 /* Quick lockable sanity check.
407 * TODO: remove this after surfaces, usage and lockability have been debugged properly
408 * this function is too deep to need to care about things like this.
409 * Levels need to be checked too, since they all affect what can be done. */
410 switch (pool)
412 case WINED3DPOOL_SCRATCH:
413 if(!lockable)
415 FIXME("Called with a pool of SCRATCH and a lockable of FALSE "
416 "which are mutually exclusive, setting lockable to TRUE.\n");
417 lockable = TRUE;
419 break;
421 case WINED3DPOOL_SYSTEMMEM:
422 if (!lockable)
423 FIXME("Called with a pool of SYSTEMMEM and a lockable of FALSE, this is acceptable but unexpected.\n");
424 break;
426 case WINED3DPOOL_MANAGED:
427 if (usage & WINED3DUSAGE_DYNAMIC)
428 FIXME("Called with a pool of MANAGED and a usage of DYNAMIC which are mutually exclusive.\n");
429 break;
431 case WINED3DPOOL_DEFAULT:
432 if (lockable && !(usage & (WINED3DUSAGE_DYNAMIC | WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL)))
433 WARN("Creating a lockable surface with a POOL of DEFAULT, that doesn't specify DYNAMIC usage.\n");
434 break;
436 default:
437 FIXME("Unknown pool %#x.\n", pool);
438 break;
441 if (usage & WINED3DUSAGE_RENDERTARGET && pool != WINED3DPOOL_DEFAULT)
443 FIXME("Trying to create a render target that isn't in the default pool.\n");
446 /* Mark the texture as dirty so that it gets loaded first time around. */
447 surface_add_dirty_rect(surface, NULL);
448 list_init(&surface->renderbuffers);
450 TRACE("surface %p, memory %p, size %u\n", surface, surface->resource.allocatedMemory, surface->resource.size);
452 /* Call the private setup routine */
453 hr = IWineD3DSurface_PrivateSetup((IWineD3DSurface *)surface);
454 if (FAILED(hr))
456 ERR("Private setup failed, returning %#x\n", hr);
457 cleanup(surface);
458 return hr;
461 return hr;
464 static void surface_force_reload(IWineD3DSurfaceImpl *surface)
466 surface->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
469 void surface_set_texture_name(IWineD3DSurfaceImpl *surface, GLuint new_name, BOOL srgb)
471 GLuint *name;
472 DWORD flag;
474 TRACE("surface %p, new_name %u, srgb %#x.\n", surface, new_name, srgb);
476 if(srgb)
478 name = &surface->texture_name_srgb;
479 flag = SFLAG_INSRGBTEX;
481 else
483 name = &surface->texture_name;
484 flag = SFLAG_INTEXTURE;
487 if (!*name && new_name)
489 /* FIXME: We shouldn't need to remove SFLAG_INTEXTURE if the
490 * surface has no texture name yet. See if we can get rid of this. */
491 if (surface->Flags & flag)
492 ERR("Surface has SFLAG_INTEXTURE set, but no texture name\n");
493 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)surface, flag, FALSE);
496 *name = new_name;
497 surface_force_reload(surface);
500 void surface_set_texture_target(IWineD3DSurfaceImpl *surface, GLenum target)
502 TRACE("surface %p, target %#x.\n", surface, target);
504 if (surface->texture_target != target)
506 if (target == GL_TEXTURE_RECTANGLE_ARB)
508 surface->Flags &= ~SFLAG_NORMCOORD;
510 else if (surface->texture_target == GL_TEXTURE_RECTANGLE_ARB)
512 surface->Flags |= SFLAG_NORMCOORD;
515 surface->texture_target = target;
516 surface_force_reload(surface);
519 /* Context activation is done by the caller. */
520 static void surface_bind_and_dirtify(IWineD3DSurfaceImpl *This, BOOL srgb) {
521 DWORD active_sampler;
523 /* We don't need a specific texture unit, but after binding the texture the current unit is dirty.
524 * Read the unit back instead of switching to 0, this avoids messing around with the state manager's
525 * gl states. The current texture unit should always be a valid one.
527 * To be more specific, this is tricky because we can implicitly be called
528 * from sampler() in state.c. This means we can't touch anything other than
529 * whatever happens to be the currently active texture, or we would risk
530 * marking already applied sampler states dirty again.
532 * TODO: Track the current active texture per GL context instead of using glGet
534 GLint active_texture;
535 ENTER_GL();
536 glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
537 LEAVE_GL();
538 active_sampler = This->resource.device->rev_tex_unit_map[active_texture - GL_TEXTURE0_ARB];
540 if (active_sampler != WINED3D_UNMAPPED_STAGE)
542 IWineD3DDeviceImpl_MarkStateDirty(This->resource.device, STATE_SAMPLER(active_sampler));
544 IWineD3DSurface_BindTexture((IWineD3DSurface *)This, srgb);
547 /* This function checks if the primary render target uses the 8bit paletted format. */
548 static BOOL primary_render_target_is_p8(IWineD3DDeviceImpl *device)
550 if (device->render_targets && device->render_targets[0])
552 IWineD3DSurfaceImpl *render_target = device->render_targets[0];
553 if ((render_target->resource.usage & WINED3DUSAGE_RENDERTARGET)
554 && (render_target->resource.format_desc->format == WINED3DFMT_P8_UINT))
555 return TRUE;
557 return FALSE;
560 /* This call just downloads data, the caller is responsible for binding the
561 * correct texture. */
562 /* Context activation is done by the caller. */
563 static void surface_download_data(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info)
565 const struct wined3d_format_desc *format_desc = This->resource.format_desc;
567 /* Only support read back of converted P8 surfaces */
568 if (This->Flags & SFLAG_CONVERTED && format_desc->format != WINED3DFMT_P8_UINT)
570 FIXME("Read back converted textures unsupported, format=%s\n", debug_d3dformat(format_desc->format));
571 return;
574 ENTER_GL();
576 if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
578 TRACE("(%p) : Calling glGetCompressedTexImageARB level %d, format %#x, type %#x, data %p.\n",
579 This, This->texture_level, format_desc->glFormat, format_desc->glType,
580 This->resource.allocatedMemory);
582 if (This->Flags & SFLAG_PBO)
584 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
585 checkGLcall("glBindBufferARB");
586 GL_EXTCALL(glGetCompressedTexImageARB(This->texture_target, This->texture_level, NULL));
587 checkGLcall("glGetCompressedTexImageARB");
588 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
589 checkGLcall("glBindBufferARB");
591 else
593 GL_EXTCALL(glGetCompressedTexImageARB(This->texture_target,
594 This->texture_level, This->resource.allocatedMemory));
595 checkGLcall("glGetCompressedTexImageARB");
598 LEAVE_GL();
599 } else {
600 void *mem;
601 GLenum format = format_desc->glFormat;
602 GLenum type = format_desc->glType;
603 int src_pitch = 0;
604 int dst_pitch = 0;
606 /* In case of P8 the index is stored in the alpha component if the primary render target uses P8 */
607 if (format_desc->format == WINED3DFMT_P8_UINT && primary_render_target_is_p8(This->resource.device))
609 format = GL_ALPHA;
610 type = GL_UNSIGNED_BYTE;
613 if (This->Flags & SFLAG_NONPOW2) {
614 unsigned char alignment = This->resource.device->surface_alignment;
615 src_pitch = format_desc->byte_count * This->pow2Width;
616 dst_pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);
617 src_pitch = (src_pitch + alignment - 1) & ~(alignment - 1);
618 mem = HeapAlloc(GetProcessHeap(), 0, src_pitch * This->pow2Height);
619 } else {
620 mem = This->resource.allocatedMemory;
623 TRACE("(%p) : Calling glGetTexImage level %d, format %#x, type %#x, data %p\n",
624 This, This->texture_level, format, type, mem);
626 if(This->Flags & SFLAG_PBO) {
627 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
628 checkGLcall("glBindBufferARB");
630 glGetTexImage(This->texture_target, This->texture_level, format, type, NULL);
631 checkGLcall("glGetTexImage");
633 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
634 checkGLcall("glBindBufferARB");
635 } else {
636 glGetTexImage(This->texture_target, This->texture_level, format, type, mem);
637 checkGLcall("glGetTexImage");
639 LEAVE_GL();
641 if (This->Flags & SFLAG_NONPOW2) {
642 const BYTE *src_data;
643 BYTE *dst_data;
644 UINT y;
646 * Some games (e.g. warhammer 40k) don't work properly with the odd pitches, preventing
647 * the surface pitch from being used to box non-power2 textures. Instead we have to use a hack to
648 * repack the texture so that the bpp * width pitch can be used instead of bpp * pow2width.
650 * We're doing this...
652 * instead of boxing the texture :
653 * |<-texture width ->| -->pow2width| /\
654 * |111111111111111111| | |
655 * |222 Texture 222222| boxed empty | texture height
656 * |3333 Data 33333333| | |
657 * |444444444444444444| | \/
658 * ----------------------------------- |
659 * | boxed empty | boxed empty | pow2height
660 * | | | \/
661 * -----------------------------------
664 * we're repacking the data to the expected texture width
666 * |<-texture width ->| -->pow2width| /\
667 * |111111111111111111222222222222222| |
668 * |222333333333333333333444444444444| texture height
669 * |444444 | |
670 * | | \/
671 * | | |
672 * | empty | pow2height
673 * | | \/
674 * -----------------------------------
676 * == is the same as
678 * |<-texture width ->| /\
679 * |111111111111111111|
680 * |222222222222222222|texture height
681 * |333333333333333333|
682 * |444444444444444444| \/
683 * --------------------
685 * this also means that any references to allocatedMemory should work with the data as if were a
686 * standard texture with a non-power2 width instead of texture boxed up to be a power2 texture.
688 * internally the texture is still stored in a boxed format so any references to textureName will
689 * get a boxed texture with width pow2width and not a texture of width currentDesc.Width.
691 * Performance should not be an issue, because applications normally do not lock the surfaces when
692 * rendering. If an app does, the SFLAG_DYNLOCK flag will kick in and the memory copy won't be released,
693 * and doesn't have to be re-read.
695 src_data = mem;
696 dst_data = This->resource.allocatedMemory;
697 TRACE("(%p) : Repacking the surface data from pitch %d to pitch %d\n", This, src_pitch, dst_pitch);
698 for (y = 1 ; y < This->currentDesc.Height; y++) {
699 /* skip the first row */
700 src_data += src_pitch;
701 dst_data += dst_pitch;
702 memcpy(dst_data, src_data, dst_pitch);
705 HeapFree(GetProcessHeap(), 0, mem);
709 /* Surface has now been downloaded */
710 This->Flags |= SFLAG_INSYSMEM;
713 /* This call just uploads data, the caller is responsible for binding the
714 * correct texture. */
715 /* Context activation is done by the caller. */
716 static void surface_upload_data(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
717 const struct wined3d_format_desc *format_desc, BOOL srgb, const GLvoid *data)
719 GLsizei width = This->currentDesc.Width;
720 GLsizei height = This->currentDesc.Height;
721 GLenum internal;
723 if (srgb)
725 internal = format_desc->glGammaInternal;
727 else if (This->resource.usage & WINED3DUSAGE_RENDERTARGET && surface_is_offscreen(This))
729 internal = format_desc->rtInternal;
731 else
733 internal = format_desc->glInternal;
736 TRACE("This %p, internal %#x, width %d, height %d, format %#x, type %#x, data %p.\n",
737 This, internal, width, height, format_desc->glFormat, format_desc->glType, data);
738 TRACE("target %#x, level %u, resource size %u.\n",
739 This->texture_target, This->texture_level, This->resource.size);
741 if (format_desc->heightscale != 1.0f && format_desc->heightscale != 0.0f) height *= format_desc->heightscale;
743 ENTER_GL();
745 if (This->Flags & SFLAG_PBO)
747 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
748 checkGLcall("glBindBufferARB");
750 TRACE("(%p) pbo: %#x, data: %p.\n", This, This->pbo, data);
751 data = NULL;
754 if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
756 TRACE("Calling glCompressedTexSubImage2DARB.\n");
758 GL_EXTCALL(glCompressedTexSubImage2DARB(This->texture_target, This->texture_level,
759 0, 0, width, height, internal, This->resource.size, data));
760 checkGLcall("glCompressedTexSubImage2DARB");
762 else
764 TRACE("Calling glTexSubImage2D.\n");
766 glTexSubImage2D(This->texture_target, This->texture_level,
767 0, 0, width, height, format_desc->glFormat, format_desc->glType, data);
768 checkGLcall("glTexSubImage2D");
771 if (This->Flags & SFLAG_PBO)
773 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
774 checkGLcall("glBindBufferARB");
777 LEAVE_GL();
779 if (gl_info->quirks & WINED3D_QUIRK_FBO_TEX_UPDATE)
781 IWineD3DDeviceImpl *device = This->resource.device;
782 unsigned int i;
784 for (i = 0; i < device->numContexts; ++i)
786 context_surface_update(device->contexts[i], This);
791 /* This call just allocates the texture, the caller is responsible for binding
792 * the correct texture. */
793 /* Context activation is done by the caller. */
794 static void surface_allocate_surface(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
795 const struct wined3d_format_desc *format_desc, BOOL srgb)
797 BOOL enable_client_storage = FALSE;
798 GLsizei width = This->pow2Width;
799 GLsizei height = This->pow2Height;
800 const BYTE *mem = NULL;
801 GLenum internal;
803 if (srgb)
805 internal = format_desc->glGammaInternal;
807 else if (This->resource.usage & WINED3DUSAGE_RENDERTARGET && surface_is_offscreen(This))
809 internal = format_desc->rtInternal;
811 else
813 internal = format_desc->glInternal;
816 if (format_desc->heightscale != 1.0f && format_desc->heightscale != 0.0f) height *= format_desc->heightscale;
818 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",
819 This, This->texture_target, This->texture_level, debug_d3dformat(format_desc->format),
820 internal, width, height, format_desc->glFormat, format_desc->glType);
822 ENTER_GL();
824 if (gl_info->supported[APPLE_CLIENT_STORAGE])
826 if(This->Flags & (SFLAG_NONPOW2 | SFLAG_DIBSECTION | SFLAG_CONVERTED) || This->resource.allocatedMemory == NULL) {
827 /* In some cases we want to disable client storage.
828 * SFLAG_NONPOW2 has a bigger opengl texture than the client memory, and different pitches
829 * SFLAG_DIBSECTION: Dibsections may have read / write protections on the memory. Avoid issues...
830 * SFLAG_CONVERTED: The conversion destination memory is freed after loading the surface
831 * allocatedMemory == NULL: Not defined in the extension. Seems to disable client storage effectively
833 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
834 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
835 This->Flags &= ~SFLAG_CLIENT;
836 enable_client_storage = TRUE;
837 } else {
838 This->Flags |= SFLAG_CLIENT;
840 /* Point opengl to our allocated texture memory. Do not use resource.allocatedMemory here because
841 * it might point into a pbo. Instead use heapMemory, but get the alignment right.
843 mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
847 if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED && mem)
849 GL_EXTCALL(glCompressedTexImage2DARB(This->texture_target, This->texture_level,
850 internal, width, height, 0, This->resource.size, mem));
851 checkGLcall("glCompressedTexImage2DARB");
853 else
855 glTexImage2D(This->texture_target, This->texture_level,
856 internal, width, height, 0, format_desc->glFormat, format_desc->glType, mem);
857 checkGLcall("glTexImage2D");
860 if(enable_client_storage) {
861 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
862 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
864 LEAVE_GL();
867 /* In D3D the depth stencil dimensions have to be greater than or equal to the
868 * render target dimensions. With FBOs, the dimensions have to be an exact match. */
869 /* TODO: We should synchronize the renderbuffer's content with the texture's content. */
870 /* GL locking is done by the caller */
871 void surface_set_compatible_renderbuffer(IWineD3DSurfaceImpl *surface, unsigned int width, unsigned int height)
873 const struct wined3d_gl_info *gl_info = &surface->resource.device->adapter->gl_info;
874 renderbuffer_entry_t *entry;
875 GLuint renderbuffer = 0;
876 unsigned int src_width, src_height;
878 src_width = surface->pow2Width;
879 src_height = surface->pow2Height;
881 /* A depth stencil smaller than the render target is not valid */
882 if (width > src_width || height > src_height) return;
884 /* Remove any renderbuffer set if the sizes match */
885 if (gl_info->supported[ARB_FRAMEBUFFER_OBJECT]
886 || (width == src_width && height == src_height))
888 surface->current_renderbuffer = NULL;
889 return;
892 /* Look if we've already got a renderbuffer of the correct dimensions */
893 LIST_FOR_EACH_ENTRY(entry, &surface->renderbuffers, renderbuffer_entry_t, entry)
895 if (entry->width == width && entry->height == height)
897 renderbuffer = entry->id;
898 surface->current_renderbuffer = entry;
899 break;
903 if (!renderbuffer)
905 gl_info->fbo_ops.glGenRenderbuffers(1, &renderbuffer);
906 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
907 gl_info->fbo_ops.glRenderbufferStorage(GL_RENDERBUFFER,
908 surface->resource.format_desc->glInternal, width, height);
910 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(renderbuffer_entry_t));
911 entry->width = width;
912 entry->height = height;
913 entry->id = renderbuffer;
914 list_add_head(&surface->renderbuffers, &entry->entry);
916 surface->current_renderbuffer = entry;
919 checkGLcall("set_compatible_renderbuffer");
922 GLenum surface_get_gl_buffer(IWineD3DSurfaceImpl *surface)
924 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)surface->container;
926 TRACE("surface %p.\n", surface);
928 if (!(surface->Flags & SFLAG_SWAPCHAIN))
930 ERR("Surface %p is not on a swapchain.\n", surface);
931 return GL_NONE;
934 if (swapchain->back_buffers && swapchain->back_buffers[0] == surface)
936 if (swapchain->render_to_fbo)
938 TRACE("Returning GL_COLOR_ATTACHMENT0\n");
939 return GL_COLOR_ATTACHMENT0;
941 TRACE("Returning GL_BACK\n");
942 return GL_BACK;
944 else if (surface == swapchain->front_buffer)
946 TRACE("Returning GL_FRONT\n");
947 return GL_FRONT;
950 FIXME("Higher back buffer, returning GL_BACK\n");
951 return GL_BACK;
954 /* Slightly inefficient way to handle multiple dirty rects but it works :) */
955 void surface_add_dirty_rect(IWineD3DSurfaceImpl *surface, const RECT *dirty_rect)
957 IWineD3DBaseTexture *baseTexture = NULL;
959 TRACE("surface %p, dirty_rect %s.\n", surface, wine_dbgstr_rect(dirty_rect));
961 if (!(surface->Flags & SFLAG_INSYSMEM) && (surface->Flags & SFLAG_INTEXTURE))
962 /* No partial locking for textures yet. */
963 IWineD3DSurface_LoadLocation((IWineD3DSurface *)surface, SFLAG_INSYSMEM, NULL);
965 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)surface, SFLAG_INSYSMEM, TRUE);
966 if (dirty_rect)
968 surface->dirtyRect.left = min(surface->dirtyRect.left, dirty_rect->left);
969 surface->dirtyRect.top = min(surface->dirtyRect.top, dirty_rect->top);
970 surface->dirtyRect.right = max(surface->dirtyRect.right, dirty_rect->right);
971 surface->dirtyRect.bottom = max(surface->dirtyRect.bottom, dirty_rect->bottom);
973 else
975 surface->dirtyRect.left = 0;
976 surface->dirtyRect.top = 0;
977 surface->dirtyRect.right = surface->currentDesc.Width;
978 surface->dirtyRect.bottom = surface->currentDesc.Height;
981 /* if the container is a basetexture then mark it dirty. */
982 if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)surface,
983 &IID_IWineD3DBaseTexture, (void **)&baseTexture)))
985 TRACE("Passing to container\n");
986 IWineD3DBaseTexture_SetDirty(baseTexture, TRUE);
987 IWineD3DBaseTexture_Release(baseTexture);
991 static BOOL surface_convert_color_to_argb(IWineD3DSurfaceImpl *This, DWORD color, DWORD *argb_color)
993 IWineD3DDeviceImpl *device = This->resource.device;
995 switch(This->resource.format_desc->format)
997 case WINED3DFMT_P8_UINT:
999 DWORD alpha;
1001 if (primary_render_target_is_p8(device))
1002 alpha = color << 24;
1003 else
1004 alpha = 0xFF000000;
1006 if (This->palette) {
1007 *argb_color = (alpha |
1008 (This->palette->palents[color].peRed << 16) |
1009 (This->palette->palents[color].peGreen << 8) |
1010 (This->palette->palents[color].peBlue));
1011 } else {
1012 *argb_color = alpha;
1015 break;
1017 case WINED3DFMT_B5G6R5_UNORM:
1019 if (color == 0xFFFF) {
1020 *argb_color = 0xFFFFFFFF;
1021 } else {
1022 *argb_color = ((0xFF000000) |
1023 ((color & 0xF800) << 8) |
1024 ((color & 0x07E0) << 5) |
1025 ((color & 0x001F) << 3));
1028 break;
1030 case WINED3DFMT_B8G8R8_UNORM:
1031 case WINED3DFMT_B8G8R8X8_UNORM:
1032 *argb_color = 0xFF000000 | color;
1033 break;
1035 case WINED3DFMT_B8G8R8A8_UNORM:
1036 *argb_color = color;
1037 break;
1039 default:
1040 ERR("Unhandled conversion from %s to ARGB!\n", debug_d3dformat(This->resource.format_desc->format));
1041 return FALSE;
1043 return TRUE;
1046 static ULONG WINAPI IWineD3DSurfaceImpl_Release(IWineD3DSurface *iface)
1048 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1049 ULONG ref = InterlockedDecrement(&This->resource.ref);
1050 TRACE("(%p) : Releasing from %d\n", This, ref + 1);
1052 if (!ref)
1054 surface_cleanup(This);
1055 This->resource.parent_ops->wined3d_object_destroyed(This->resource.parent);
1057 TRACE("(%p) Released.\n", This);
1058 HeapFree(GetProcessHeap(), 0, This);
1061 return ref;
1064 /* ****************************************************
1065 IWineD3DSurface IWineD3DResource parts follow
1066 **************************************************** */
1068 void surface_internal_preload(IWineD3DSurfaceImpl *surface, enum WINED3DSRGB srgb)
1070 /* TODO: check for locks */
1071 IWineD3DDeviceImpl *device = surface->resource.device;
1072 IWineD3DBaseTexture *baseTexture = NULL;
1074 TRACE("(%p)Checking to see if the container is a base texture\n", surface);
1075 if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)surface,
1076 &IID_IWineD3DBaseTexture, (void **)&baseTexture)))
1078 IWineD3DBaseTextureImpl *tex_impl = (IWineD3DBaseTextureImpl *)baseTexture;
1079 TRACE("Passing to container\n");
1080 tex_impl->baseTexture.internal_preload(baseTexture, srgb);
1081 IWineD3DBaseTexture_Release(baseTexture);
1082 } else {
1083 struct wined3d_context *context = NULL;
1085 TRACE("(%p) : About to load surface\n", surface);
1087 if (!device->isInDraw) context = context_acquire(device, NULL);
1089 if (surface->resource.format_desc->format == WINED3DFMT_P8_UINT
1090 || surface->resource.format_desc->format == WINED3DFMT_P8_UINT_A8_UNORM)
1092 if (palette9_changed(surface))
1094 TRACE("Reloading surface because the d3d8/9 palette was changed\n");
1095 /* TODO: This is not necessarily needed with hw palettized texture support */
1096 IWineD3DSurface_LoadLocation((IWineD3DSurface *)surface, SFLAG_INSYSMEM, NULL);
1097 /* Make sure the texture is reloaded because of the palette change, this kills performance though :( */
1098 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)surface, SFLAG_INTEXTURE, FALSE);
1102 IWineD3DSurface_LoadTexture((IWineD3DSurface *)surface, srgb == SRGB_SRGB ? TRUE : FALSE);
1104 if (surface->resource.pool == WINED3DPOOL_DEFAULT)
1106 /* Tell opengl to try and keep this texture in video ram (well mostly) */
1107 GLclampf tmp;
1108 tmp = 0.9f;
1109 ENTER_GL();
1110 glPrioritizeTextures(1, &surface->texture_name, &tmp);
1111 LEAVE_GL();
1114 if (context) context_release(context);
1118 static void WINAPI IWineD3DSurfaceImpl_PreLoad(IWineD3DSurface *iface)
1120 surface_internal_preload((IWineD3DSurfaceImpl *)iface, SRGB_ANY);
1123 /* Context activation is done by the caller. */
1124 static void surface_remove_pbo(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info)
1126 This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
1127 This->resource.allocatedMemory =
1128 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1130 ENTER_GL();
1131 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1132 checkGLcall("glBindBufferARB(GL_PIXEL_UNPACK_BUFFER, This->pbo)");
1133 GL_EXTCALL(glGetBufferSubDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0, This->resource.size, This->resource.allocatedMemory));
1134 checkGLcall("glGetBufferSubDataARB");
1135 GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
1136 checkGLcall("glDeleteBuffersARB");
1137 LEAVE_GL();
1139 This->pbo = 0;
1140 This->Flags &= ~SFLAG_PBO;
1143 BOOL surface_init_sysmem(IWineD3DSurfaceImpl *surface)
1145 if (!surface->resource.allocatedMemory)
1147 surface->resource.heapMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1148 surface->resource.size + RESOURCE_ALIGNMENT);
1149 if (!surface->resource.heapMemory)
1151 ERR("Out of memory\n");
1152 return FALSE;
1154 surface->resource.allocatedMemory =
1155 (BYTE *)(((ULONG_PTR)surface->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1157 else
1159 memset(surface->resource.allocatedMemory, 0, surface->resource.size);
1162 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)surface, SFLAG_INSYSMEM, TRUE);
1163 return TRUE;
1166 static void WINAPI IWineD3DSurfaceImpl_UnLoad(IWineD3DSurface *iface) {
1167 IWineD3DBaseTexture *texture = NULL;
1168 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
1169 IWineD3DDeviceImpl *device = This->resource.device;
1170 const struct wined3d_gl_info *gl_info;
1171 renderbuffer_entry_t *entry, *entry2;
1172 struct wined3d_context *context;
1174 TRACE("(%p)\n", iface);
1176 if(This->resource.pool == WINED3DPOOL_DEFAULT) {
1177 /* Default pool resources are supposed to be destroyed before Reset is called.
1178 * Implicit resources stay however. So this means we have an implicit render target
1179 * or depth stencil. The content may be destroyed, but we still have to tear down
1180 * opengl resources, so we cannot leave early.
1182 * Put the surfaces into sysmem, and reset the content. The D3D content is undefined,
1183 * but we can't set the sysmem INDRAWABLE because when we're rendering the swapchain
1184 * or the depth stencil into an FBO the texture or render buffer will be removed
1185 * and all flags get lost
1187 surface_init_sysmem(This);
1189 else
1191 /* Load the surface into system memory */
1192 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
1193 IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, FALSE);
1195 IWineD3DSurface_ModifyLocation(iface, SFLAG_INTEXTURE, FALSE);
1196 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSRGBTEX, FALSE);
1197 This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
1199 context = context_acquire(device, NULL);
1200 gl_info = context->gl_info;
1202 /* Destroy PBOs, but load them into real sysmem before */
1203 if (This->Flags & SFLAG_PBO)
1204 surface_remove_pbo(This, gl_info);
1206 /* Destroy fbo render buffers. This is needed for implicit render targets, for
1207 * all application-created targets the application has to release the surface
1208 * before calling _Reset
1210 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
1211 ENTER_GL();
1212 gl_info->fbo_ops.glDeleteRenderbuffers(1, &entry->id);
1213 LEAVE_GL();
1214 list_remove(&entry->entry);
1215 HeapFree(GetProcessHeap(), 0, entry);
1217 list_init(&This->renderbuffers);
1218 This->current_renderbuffer = NULL;
1220 /* If we're in a texture, the texture name belongs to the texture. Otherwise,
1221 * destroy it
1223 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **) &texture);
1224 if(!texture) {
1225 ENTER_GL();
1226 glDeleteTextures(1, &This->texture_name);
1227 This->texture_name = 0;
1228 glDeleteTextures(1, &This->texture_name_srgb);
1229 This->texture_name_srgb = 0;
1230 LEAVE_GL();
1231 } else {
1232 IWineD3DBaseTexture_Release(texture);
1235 context_release(context);
1238 /* ******************************************************
1239 IWineD3DSurface IWineD3DSurface parts follow
1240 ****************************************************** */
1242 /* Read the framebuffer back into the surface */
1243 static void read_from_framebuffer(IWineD3DSurfaceImpl *This, const RECT *rect, void *dest, UINT pitch)
1245 IWineD3DDeviceImpl *device = This->resource.device;
1246 const struct wined3d_gl_info *gl_info;
1247 struct wined3d_context *context;
1248 BYTE *mem;
1249 GLint fmt;
1250 GLint type;
1251 BYTE *row, *top, *bottom;
1252 int i;
1253 BOOL bpp;
1254 RECT local_rect;
1255 BOOL srcIsUpsideDown;
1256 GLint rowLen = 0;
1257 GLint skipPix = 0;
1258 GLint skipRow = 0;
1260 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1261 static BOOL warned = FALSE;
1262 if(!warned) {
1263 ERR("The application tries to lock the render target, but render target locking is disabled\n");
1264 warned = TRUE;
1266 return;
1269 /* Activate the surface. Set it up for blitting now, although not necessarily needed for LockRect.
1270 * Certain graphics drivers seem to dislike some enabled states when reading from opengl, the blitting usage
1271 * should help here. Furthermore unlockrect will need the context set up for blitting. The context manager will find
1272 * context->last_was_blit set on the unlock.
1274 context = context_acquire(device, This);
1275 context_apply_blit_state(context, device);
1276 gl_info = context->gl_info;
1278 ENTER_GL();
1280 /* Select the correct read buffer, and give some debug output.
1281 * There is no need to keep track of the current read buffer or reset it, every part of the code
1282 * that reads sets the read buffer as desired.
1284 if (surface_is_offscreen(This))
1286 /* Locking the primary render target which is not on a swapchain(=offscreen render target).
1287 * Read from the back buffer
1289 TRACE("Locking offscreen render target\n");
1290 glReadBuffer(device->offscreenBuffer);
1291 srcIsUpsideDown = TRUE;
1293 else
1295 /* Onscreen surfaces are always part of a swapchain */
1296 GLenum buffer = surface_get_gl_buffer(This);
1297 TRACE("Locking %#x buffer\n", buffer);
1298 glReadBuffer(buffer);
1299 checkGLcall("glReadBuffer");
1300 srcIsUpsideDown = FALSE;
1303 /* TODO: Get rid of the extra rectangle comparison and construction of a full surface rectangle */
1304 if(!rect) {
1305 local_rect.left = 0;
1306 local_rect.top = 0;
1307 local_rect.right = This->currentDesc.Width;
1308 local_rect.bottom = This->currentDesc.Height;
1309 } else {
1310 local_rect = *rect;
1312 /* TODO: Get rid of the extra GetPitch call, LockRect does that too. Cache the pitch */
1314 switch(This->resource.format_desc->format)
1316 case WINED3DFMT_P8_UINT:
1318 if (primary_render_target_is_p8(device))
1320 /* In case of P8 render targets the index is stored in the alpha component */
1321 fmt = GL_ALPHA;
1322 type = GL_UNSIGNED_BYTE;
1323 mem = dest;
1324 bpp = This->resource.format_desc->byte_count;
1325 } else {
1326 /* GL can't return palettized data, so read ARGB pixels into a
1327 * separate block of memory and convert them into palettized format
1328 * in software. Slow, but if the app means to use palettized render
1329 * targets and locks it...
1331 * Use GL_RGB, GL_UNSIGNED_BYTE to read the surface for performance reasons
1332 * Don't use GL_BGR as in the WINED3DFMT_R8G8B8 case, instead watch out
1333 * for the color channels when palettizing the colors.
1335 fmt = GL_RGB;
1336 type = GL_UNSIGNED_BYTE;
1337 pitch *= 3;
1338 mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * 3);
1339 if(!mem) {
1340 ERR("Out of memory\n");
1341 LEAVE_GL();
1342 return;
1344 bpp = This->resource.format_desc->byte_count * 3;
1347 break;
1349 default:
1350 mem = dest;
1351 fmt = This->resource.format_desc->glFormat;
1352 type = This->resource.format_desc->glType;
1353 bpp = This->resource.format_desc->byte_count;
1356 if(This->Flags & SFLAG_PBO) {
1357 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
1358 checkGLcall("glBindBufferARB");
1359 if(mem != NULL) {
1360 ERR("mem not null for pbo -- unexpected\n");
1361 mem = NULL;
1365 /* Save old pixel store pack state */
1366 glGetIntegerv(GL_PACK_ROW_LENGTH, &rowLen);
1367 checkGLcall("glGetIntegerv");
1368 glGetIntegerv(GL_PACK_SKIP_PIXELS, &skipPix);
1369 checkGLcall("glGetIntegerv");
1370 glGetIntegerv(GL_PACK_SKIP_ROWS, &skipRow);
1371 checkGLcall("glGetIntegerv");
1373 /* Setup pixel store pack state -- to glReadPixels into the correct place */
1374 glPixelStorei(GL_PACK_ROW_LENGTH, This->currentDesc.Width);
1375 checkGLcall("glPixelStorei");
1376 glPixelStorei(GL_PACK_SKIP_PIXELS, local_rect.left);
1377 checkGLcall("glPixelStorei");
1378 glPixelStorei(GL_PACK_SKIP_ROWS, local_rect.top);
1379 checkGLcall("glPixelStorei");
1381 glReadPixels(local_rect.left, (!srcIsUpsideDown) ? (This->currentDesc.Height - local_rect.bottom) : local_rect.top ,
1382 local_rect.right - local_rect.left,
1383 local_rect.bottom - local_rect.top,
1384 fmt, type, mem);
1385 checkGLcall("glReadPixels");
1387 /* Reset previous pixel store pack state */
1388 glPixelStorei(GL_PACK_ROW_LENGTH, rowLen);
1389 checkGLcall("glPixelStorei");
1390 glPixelStorei(GL_PACK_SKIP_PIXELS, skipPix);
1391 checkGLcall("glPixelStorei");
1392 glPixelStorei(GL_PACK_SKIP_ROWS, skipRow);
1393 checkGLcall("glPixelStorei");
1395 if(This->Flags & SFLAG_PBO) {
1396 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
1397 checkGLcall("glBindBufferARB");
1399 /* Check if we need to flip the image. If we need to flip use glMapBufferARB
1400 * to get a pointer to it and perform the flipping in software. This is a lot
1401 * faster than calling glReadPixels for each line. In case we want more speed
1402 * we should rerender it flipped in a FBO and read the data back from the FBO. */
1403 if(!srcIsUpsideDown) {
1404 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1405 checkGLcall("glBindBufferARB");
1407 mem = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1408 checkGLcall("glMapBufferARB");
1412 /* TODO: Merge this with the palettization loop below for P8 targets */
1413 if(!srcIsUpsideDown) {
1414 UINT len, off;
1415 /* glReadPixels returns the image upside down, and there is no way to prevent this.
1416 Flip the lines in software */
1417 len = (local_rect.right - local_rect.left) * bpp;
1418 off = local_rect.left * bpp;
1420 row = HeapAlloc(GetProcessHeap(), 0, len);
1421 if(!row) {
1422 ERR("Out of memory\n");
1423 if (This->resource.format_desc->format == WINED3DFMT_P8_UINT) HeapFree(GetProcessHeap(), 0, mem);
1424 LEAVE_GL();
1425 return;
1428 top = mem + pitch * local_rect.top;
1429 bottom = mem + pitch * (local_rect.bottom - 1);
1430 for(i = 0; i < (local_rect.bottom - local_rect.top) / 2; i++) {
1431 memcpy(row, top + off, len);
1432 memcpy(top + off, bottom + off, len);
1433 memcpy(bottom + off, row, len);
1434 top += pitch;
1435 bottom -= pitch;
1437 HeapFree(GetProcessHeap(), 0, row);
1439 /* Unmap the temp PBO buffer */
1440 if(This->Flags & SFLAG_PBO) {
1441 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1442 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1446 LEAVE_GL();
1447 context_release(context);
1449 /* For P8 textures we need to perform an inverse palette lookup. This is done by searching for a palette
1450 * index which matches the RGB value. Note this isn't guaranteed to work when there are multiple entries for
1451 * the same color but we have no choice.
1452 * In case of P8 render targets, the index is stored in the alpha component so no conversion is needed.
1454 if (This->resource.format_desc->format == WINED3DFMT_P8_UINT && !primary_render_target_is_p8(device))
1456 const PALETTEENTRY *pal = NULL;
1457 DWORD width = pitch / 3;
1458 int x, y, c;
1460 if(This->palette) {
1461 pal = This->palette->palents;
1462 } else {
1463 ERR("Palette is missing, cannot perform inverse palette lookup\n");
1464 HeapFree(GetProcessHeap(), 0, mem);
1465 return ;
1468 for(y = local_rect.top; y < local_rect.bottom; y++) {
1469 for(x = local_rect.left; x < local_rect.right; x++) {
1470 /* start lines pixels */
1471 const BYTE *blue = mem + y * pitch + x * (sizeof(BYTE) * 3);
1472 const BYTE *green = blue + 1;
1473 const BYTE *red = green + 1;
1475 for(c = 0; c < 256; c++) {
1476 if(*red == pal[c].peRed &&
1477 *green == pal[c].peGreen &&
1478 *blue == pal[c].peBlue)
1480 *((BYTE *) dest + y * width + x) = c;
1481 break;
1486 HeapFree(GetProcessHeap(), 0, mem);
1490 /* Read the framebuffer contents into a texture */
1491 static void read_from_framebuffer_texture(IWineD3DSurfaceImpl *This, BOOL srgb)
1493 IWineD3DDeviceImpl *device = This->resource.device;
1494 const struct wined3d_gl_info *gl_info;
1495 struct wined3d_context *context;
1496 GLint prevRead;
1498 /* Activate the surface to read from. In some situations it isn't the currently active target(e.g. backbuffer
1499 * locking during offscreen rendering). RESOURCELOAD is ok because glCopyTexSubImage2D isn't affected by any
1500 * states in the stateblock, and no driver was found yet that had bugs in that regard.
1502 context = context_acquire(device, This);
1503 gl_info = context->gl_info;
1505 surface_prepare_texture(This, gl_info, srgb);
1506 surface_bind_and_dirtify(This, srgb);
1508 ENTER_GL();
1509 glGetIntegerv(GL_READ_BUFFER, &prevRead);
1510 LEAVE_GL();
1512 /* Select the correct read buffer, and give some debug output.
1513 * There is no need to keep track of the current read buffer or reset it, every part of the code
1514 * that reads sets the read buffer as desired.
1516 if (!surface_is_offscreen(This))
1518 GLenum buffer = surface_get_gl_buffer(This);
1519 TRACE("Locking %#x buffer\n", buffer);
1521 ENTER_GL();
1522 glReadBuffer(buffer);
1523 checkGLcall("glReadBuffer");
1524 LEAVE_GL();
1526 else
1528 /* Locking the primary render target which is not on a swapchain(=offscreen render target).
1529 * Read from the back buffer
1531 TRACE("Locking offscreen render target\n");
1532 ENTER_GL();
1533 glReadBuffer(device->offscreenBuffer);
1534 checkGLcall("glReadBuffer");
1535 LEAVE_GL();
1538 ENTER_GL();
1539 /* If !SrcIsUpsideDown we should flip the surface.
1540 * This can be done using glCopyTexSubImage2D but this
1541 * is VERY slow, so don't do that. We should prevent
1542 * this code from getting called in such cases or perhaps
1543 * we can use FBOs */
1545 glCopyTexSubImage2D(This->texture_target, This->texture_level,
1546 0, 0, 0, 0, This->currentDesc.Width, This->currentDesc.Height);
1547 checkGLcall("glCopyTexSubImage2D");
1549 glReadBuffer(prevRead);
1550 checkGLcall("glReadBuffer");
1552 LEAVE_GL();
1554 context_release(context);
1556 TRACE("Updated target %d\n", This->texture_target);
1559 /* Context activation is done by the caller. */
1560 static void surface_prepare_texture_internal(IWineD3DSurfaceImpl *surface,
1561 const struct wined3d_gl_info *gl_info, BOOL srgb)
1563 DWORD alloc_flag = srgb ? SFLAG_SRGBALLOCATED : SFLAG_ALLOCATED;
1564 CONVERT_TYPES convert;
1565 struct wined3d_format_desc desc;
1567 if (surface->Flags & alloc_flag) return;
1569 d3dfmt_get_conv(surface, TRUE, TRUE, &desc, &convert);
1570 if(convert != NO_CONVERSION || desc.convert) surface->Flags |= SFLAG_CONVERTED;
1571 else surface->Flags &= ~SFLAG_CONVERTED;
1573 surface_bind_and_dirtify(surface, srgb);
1574 surface_allocate_surface(surface, gl_info, &desc, srgb);
1575 surface->Flags |= alloc_flag;
1578 /* Context activation is done by the caller. */
1579 void surface_prepare_texture(IWineD3DSurfaceImpl *surface, const struct wined3d_gl_info *gl_info, BOOL srgb)
1581 IWineD3DBaseTextureImpl *texture;
1583 if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)surface,
1584 &IID_IWineD3DBaseTexture, (void **)&texture)))
1586 UINT sub_count = texture->baseTexture.level_count * texture->baseTexture.layer_count;
1587 UINT i;
1589 TRACE("surface %p is a subresource of texture %p.\n", surface, texture);
1591 for (i = 0; i < sub_count; ++i)
1593 IWineD3DSurfaceImpl *s = (IWineD3DSurfaceImpl *)texture->baseTexture.sub_resources[i];
1594 surface_prepare_texture_internal(s, gl_info, srgb);
1597 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture);
1600 surface_prepare_texture_internal(surface, gl_info, srgb);
1603 static void surface_prepare_system_memory(IWineD3DSurfaceImpl *This)
1605 IWineD3DDeviceImpl *device = This->resource.device;
1606 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1608 /* Performance optimization: Count how often a surface is locked, if it is locked regularly do not throw away the system memory copy.
1609 * This avoids the need to download the surface from opengl all the time. The surface is still downloaded if the opengl texture is
1610 * changed
1612 if(!(This->Flags & SFLAG_DYNLOCK)) {
1613 This->lockCount++;
1614 /* MAXLOCKCOUNT is defined in wined3d_private.h */
1615 if(This->lockCount > MAXLOCKCOUNT) {
1616 TRACE("Surface is locked regularly, not freeing the system memory copy any more\n");
1617 This->Flags |= SFLAG_DYNLOCK;
1621 /* Create a PBO for dynamically locked surfaces but don't do it for converted or non-pow2 surfaces.
1622 * Also don't create a PBO for systemmem surfaces.
1624 if (gl_info->supported[ARB_PIXEL_BUFFER_OBJECT] && (This->Flags & SFLAG_DYNLOCK)
1625 && !(This->Flags & (SFLAG_PBO | SFLAG_CONVERTED | SFLAG_NONPOW2))
1626 && (This->resource.pool != WINED3DPOOL_SYSTEMMEM))
1628 GLenum error;
1629 struct wined3d_context *context;
1631 context = context_acquire(device, NULL);
1632 ENTER_GL();
1634 GL_EXTCALL(glGenBuffersARB(1, &This->pbo));
1635 error = glGetError();
1636 if(This->pbo == 0 || error != GL_NO_ERROR) {
1637 ERR("Failed to bind the PBO with error %s (%#x)\n", debug_glerror(error), error);
1640 TRACE("Attaching pbo=%#x to (%p)\n", This->pbo, This);
1642 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1643 checkGLcall("glBindBufferARB");
1645 GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->resource.size + 4, This->resource.allocatedMemory, GL_STREAM_DRAW_ARB));
1646 checkGLcall("glBufferDataARB");
1648 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1649 checkGLcall("glBindBufferARB");
1651 /* We don't need the system memory anymore and we can't even use it for PBOs */
1652 if(!(This->Flags & SFLAG_CLIENT)) {
1653 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
1654 This->resource.heapMemory = NULL;
1656 This->resource.allocatedMemory = NULL;
1657 This->Flags |= SFLAG_PBO;
1658 LEAVE_GL();
1659 context_release(context);
1661 else if (!(This->resource.allocatedMemory || This->Flags & SFLAG_PBO))
1663 /* Whatever surface we have, make sure that there is memory allocated for the downloaded copy,
1664 * or a pbo to map
1666 if(!This->resource.heapMemory) {
1667 This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
1669 This->resource.allocatedMemory =
1670 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1671 if(This->Flags & SFLAG_INSYSMEM) {
1672 ERR("Surface without memory or pbo has SFLAG_INSYSMEM set!\n");
1677 static HRESULT WINAPI IWineD3DSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags) {
1678 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1679 IWineD3DDeviceImpl *device = This->resource.device;
1680 const RECT *pass_rect = pRect;
1682 TRACE("iface %p, locked_rect %p, rect %s, flags %#x.\n",
1683 iface, pLockedRect, wine_dbgstr_rect(pRect), Flags);
1685 /* This is also done in the base class, but we have to verify this before loading any data from
1686 * gl into the sysmem copy. The PBO may be mapped, a different rectangle locked, the discard flag
1687 * may interfere, and all other bad things may happen
1689 if (This->Flags & SFLAG_LOCKED) {
1690 WARN("Surface is already locked, returning D3DERR_INVALIDCALL\n");
1691 return WINED3DERR_INVALIDCALL;
1693 This->Flags |= SFLAG_LOCKED;
1695 if (!(This->Flags & SFLAG_LOCKABLE))
1697 TRACE("Warning: trying to lock unlockable surf@%p\n", This);
1700 if (Flags & WINED3DLOCK_DISCARD) {
1701 /* Set SFLAG_INSYSMEM, so we'll never try to download the data from the texture. */
1702 TRACE("WINED3DLOCK_DISCARD flag passed, marking local copy as up to date\n");
1703 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1704 This->Flags |= SFLAG_INSYSMEM;
1705 goto lock_end;
1708 if (This->Flags & SFLAG_INSYSMEM) {
1709 TRACE("Local copy is up to date, not downloading data\n");
1710 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1711 goto lock_end;
1714 /* IWineD3DSurface_LoadLocation() does not check if the rectangle specifies
1715 * the full surface. Most callers don't need that, so do it here. */
1716 if (pRect && pRect->top == 0 && pRect->left == 0
1717 && pRect->right == This->currentDesc.Width
1718 && pRect->bottom == This->currentDesc.Height)
1720 pass_rect = NULL;
1723 if (!(wined3d_settings.rendertargetlock_mode == RTL_DISABLE
1724 && ((This->Flags & SFLAG_SWAPCHAIN) || This == device->render_targets[0])))
1726 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, pass_rect);
1729 lock_end:
1730 if (This->Flags & SFLAG_PBO)
1732 const struct wined3d_gl_info *gl_info;
1733 struct wined3d_context *context;
1735 context = context_acquire(device, NULL);
1736 gl_info = context->gl_info;
1738 ENTER_GL();
1739 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1740 checkGLcall("glBindBufferARB");
1742 /* This shouldn't happen but could occur if some other function didn't handle the PBO properly */
1743 if(This->resource.allocatedMemory) {
1744 ERR("The surface already has PBO memory allocated!\n");
1747 This->resource.allocatedMemory = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1748 checkGLcall("glMapBufferARB");
1750 /* Make sure the pbo isn't set anymore in order not to break non-pbo calls */
1751 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1752 checkGLcall("glBindBufferARB");
1754 LEAVE_GL();
1755 context_release(context);
1758 if (Flags & (WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY)) {
1759 /* Don't dirtify */
1760 } else {
1761 IWineD3DBaseTexture *pBaseTexture;
1763 * Dirtify on lock
1764 * as seen in msdn docs
1766 surface_add_dirty_rect(This, pRect);
1768 /** Dirtify Container if needed */
1769 if (SUCCEEDED(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&pBaseTexture))) {
1770 TRACE("Making container dirty\n");
1771 IWineD3DBaseTexture_SetDirty(pBaseTexture, TRUE);
1772 IWineD3DBaseTexture_Release(pBaseTexture);
1773 } else {
1774 TRACE("Surface is standalone, no need to dirty the container\n");
1778 return IWineD3DBaseSurfaceImpl_LockRect(iface, pLockedRect, pRect, Flags);
1781 static void flush_to_framebuffer_drawpixels(IWineD3DSurfaceImpl *This, GLenum fmt, GLenum type, UINT bpp, const BYTE *mem) {
1782 GLint prev_store;
1783 GLint prev_rasterpos[4];
1784 GLint skipBytes = 0;
1785 UINT pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This); /* target is argb, 4 byte */
1786 IWineD3DDeviceImpl *device = This->resource.device;
1787 const struct wined3d_gl_info *gl_info;
1788 struct wined3d_context *context;
1790 /* Activate the correct context for the render target */
1791 context = context_acquire(device, This);
1792 context_apply_blit_state(context, device);
1793 gl_info = context->gl_info;
1795 ENTER_GL();
1797 if (!surface_is_offscreen(This))
1799 GLenum buffer = surface_get_gl_buffer(This);
1800 TRACE("Unlocking %#x buffer.\n", buffer);
1801 context_set_draw_buffer(context, buffer);
1803 else
1805 /* Primary offscreen render target */
1806 TRACE("Offscreen render target.\n");
1807 context_set_draw_buffer(context, device->offscreenBuffer);
1810 glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
1811 checkGLcall("glGetIntegerv");
1812 glGetIntegerv(GL_CURRENT_RASTER_POSITION, &prev_rasterpos[0]);
1813 checkGLcall("glGetIntegerv");
1814 glPixelZoom(1.0f, -1.0f);
1815 checkGLcall("glPixelZoom");
1817 /* If not fullscreen, we need to skip a number of bytes to find the next row of data */
1818 glGetIntegerv(GL_UNPACK_ROW_LENGTH, &skipBytes);
1819 glPixelStorei(GL_UNPACK_ROW_LENGTH, This->currentDesc.Width);
1821 glRasterPos3i(This->lockedRect.left, This->lockedRect.top, 1);
1822 checkGLcall("glRasterPos3i");
1824 /* Some drivers(radeon dri, others?) don't like exceptions during
1825 * glDrawPixels. If the surface is a DIB section, it might be in GDIMode
1826 * after ReleaseDC. Reading it will cause an exception, which x11drv will
1827 * catch to put the dib section in InSync mode, which leads to a crash
1828 * and a blocked x server on my radeon card.
1830 * The following lines read the dib section so it is put in InSync mode
1831 * before glDrawPixels is called and the crash is prevented. There won't
1832 * be any interfering gdi accesses, because UnlockRect is called from
1833 * ReleaseDC, and the app won't use the dc any more afterwards.
1835 if((This->Flags & SFLAG_DIBSECTION) && !(This->Flags & SFLAG_PBO)) {
1836 volatile BYTE read;
1837 read = This->resource.allocatedMemory[0];
1840 if(This->Flags & SFLAG_PBO) {
1841 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1842 checkGLcall("glBindBufferARB");
1845 /* When the surface is locked we only have to refresh the locked part else we need to update the whole image */
1846 if(This->Flags & SFLAG_LOCKED) {
1847 glDrawPixels(This->lockedRect.right - This->lockedRect.left,
1848 (This->lockedRect.bottom - This->lockedRect.top)-1,
1849 fmt, type,
1850 mem + bpp * This->lockedRect.left + pitch * This->lockedRect.top);
1851 checkGLcall("glDrawPixels");
1852 } else {
1853 glDrawPixels(This->currentDesc.Width,
1854 This->currentDesc.Height,
1855 fmt, type, mem);
1856 checkGLcall("glDrawPixels");
1859 if(This->Flags & SFLAG_PBO) {
1860 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1861 checkGLcall("glBindBufferARB");
1864 glPixelZoom(1.0f, 1.0f);
1865 checkGLcall("glPixelZoom");
1867 glRasterPos3iv(&prev_rasterpos[0]);
1868 checkGLcall("glRasterPos3iv");
1870 /* Reset to previous pack row length */
1871 glPixelStorei(GL_UNPACK_ROW_LENGTH, skipBytes);
1872 checkGLcall("glPixelStorei(GL_UNPACK_ROW_LENGTH)");
1874 LEAVE_GL();
1875 context_release(context);
1878 static HRESULT WINAPI IWineD3DSurfaceImpl_UnlockRect(IWineD3DSurface *iface) {
1879 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1880 IWineD3DDeviceImpl *device = This->resource.device;
1881 BOOL fullsurface;
1883 if (!(This->Flags & SFLAG_LOCKED)) {
1884 WARN("trying to Unlock an unlocked surf@%p\n", This);
1885 return WINEDDERR_NOTLOCKED;
1888 if (This->Flags & SFLAG_PBO)
1890 const struct wined3d_gl_info *gl_info;
1891 struct wined3d_context *context;
1893 TRACE("Freeing PBO memory\n");
1895 context = context_acquire(device, NULL);
1896 gl_info = context->gl_info;
1898 ENTER_GL();
1899 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1900 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1901 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1902 checkGLcall("glUnmapBufferARB");
1903 LEAVE_GL();
1904 context_release(context);
1906 This->resource.allocatedMemory = NULL;
1909 TRACE("(%p) : dirtyfied(%d)\n", This, This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
1911 if (This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE)) {
1912 TRACE("(%p) : Not Dirtified so nothing to do, return now\n", This);
1913 goto unlock_end;
1916 if ((This->Flags & SFLAG_SWAPCHAIN) || (device->render_targets && This == device->render_targets[0]))
1918 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1919 static BOOL warned = FALSE;
1920 if(!warned) {
1921 ERR("The application tries to write to the render target, but render target locking is disabled\n");
1922 warned = TRUE;
1924 goto unlock_end;
1927 if(This->dirtyRect.left == 0 &&
1928 This->dirtyRect.top == 0 &&
1929 This->dirtyRect.right == This->currentDesc.Width &&
1930 This->dirtyRect.bottom == This->currentDesc.Height) {
1931 fullsurface = TRUE;
1932 } else {
1933 /* TODO: Proper partial rectangle tracking */
1934 fullsurface = FALSE;
1935 This->Flags |= SFLAG_INSYSMEM;
1938 switch(wined3d_settings.rendertargetlock_mode) {
1939 case RTL_READTEX:
1940 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* partial texture loading not supported yet */);
1941 /* drop through */
1943 case RTL_READDRAW:
1944 IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, fullsurface ? NULL : &This->dirtyRect);
1945 break;
1948 if(!fullsurface) {
1949 /* Partial rectangle tracking is not commonly implemented, it is only done for render targets. Overwrite
1950 * the flags to bring them back into a sane state. INSYSMEM was set before to tell LoadLocation where
1951 * to read the rectangle from. Indrawable is set because all modifications from the partial sysmem copy
1952 * are written back to the drawable, thus the surface is merged again in the drawable. The sysmem copy is
1953 * not fully up to date because only a subrectangle was read in LockRect.
1955 This->Flags &= ~SFLAG_INSYSMEM;
1956 This->Flags |= SFLAG_INDRAWABLE;
1959 This->dirtyRect.left = This->currentDesc.Width;
1960 This->dirtyRect.top = This->currentDesc.Height;
1961 This->dirtyRect.right = 0;
1962 This->dirtyRect.bottom = 0;
1964 else if (This == device->depth_stencil)
1966 FIXME("Depth Stencil buffer locking is not implemented\n");
1967 } else {
1968 /* The rest should be a normal texture */
1969 IWineD3DBaseTextureImpl *impl;
1970 /* Check if the texture is bound, if yes dirtify the sampler to force a re-upload of the texture
1971 * Can't load the texture here because PreLoad may destroy and recreate the gl texture, so sampler
1972 * states need resetting
1974 if(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&impl) == WINED3D_OK) {
1975 if (impl->baseTexture.bindCount)
1976 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(impl->baseTexture.sampler));
1977 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *) impl);
1981 unlock_end:
1982 This->Flags &= ~SFLAG_LOCKED;
1983 memset(&This->lockedRect, 0, sizeof(RECT));
1985 /* Overlays have to be redrawn manually after changes with the GL implementation */
1986 if(This->overlay_dest) {
1987 IWineD3DSurface_DrawOverlay(iface);
1989 return WINED3D_OK;
1992 static void surface_release_client_storage(IWineD3DSurfaceImpl *surface)
1994 struct wined3d_context *context;
1996 context = context_acquire(surface->resource.device, NULL);
1998 ENTER_GL();
1999 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
2000 if (surface->texture_name)
2002 surface_bind_and_dirtify(surface, FALSE);
2003 glTexImage2D(surface->texture_target, surface->texture_level,
2004 GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
2006 if (surface->texture_name_srgb)
2008 surface_bind_and_dirtify(surface, TRUE);
2009 glTexImage2D(surface->texture_target, surface->texture_level,
2010 GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
2012 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
2014 LEAVE_GL();
2015 context_release(context);
2017 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)surface, SFLAG_INSRGBTEX, FALSE);
2018 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)surface, SFLAG_INTEXTURE, FALSE);
2019 surface_force_reload(surface);
2022 static HRESULT WINAPI IWineD3DSurfaceImpl_GetDC(IWineD3DSurface *iface, HDC *pHDC)
2024 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2025 WINED3DLOCKED_RECT lock;
2026 HRESULT hr;
2027 RGBQUAD col[256];
2029 TRACE("(%p)->(%p)\n",This,pHDC);
2031 if(This->Flags & SFLAG_USERPTR) {
2032 ERR("Not supported on surfaces with an application-provided surfaces\n");
2033 return WINEDDERR_NODC;
2036 /* Give more detailed info for ddraw */
2037 if (This->Flags & SFLAG_DCINUSE)
2038 return WINEDDERR_DCALREADYCREATED;
2040 /* Can't GetDC if the surface is locked */
2041 if (This->Flags & SFLAG_LOCKED)
2042 return WINED3DERR_INVALIDCALL;
2044 memset(&lock, 0, sizeof(lock)); /* To be sure */
2046 /* Create a DIB section if there isn't a hdc yet */
2047 if(!This->hDC) {
2048 if(This->Flags & SFLAG_CLIENT) {
2049 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
2050 surface_release_client_storage(This);
2052 hr = IWineD3DBaseSurfaceImpl_CreateDIBSection(iface);
2053 if(FAILED(hr)) return WINED3DERR_INVALIDCALL;
2055 /* Use the dib section from now on if we are not using a PBO */
2056 if(!(This->Flags & SFLAG_PBO))
2057 This->resource.allocatedMemory = This->dib.bitmap_data;
2060 /* Lock the surface */
2061 hr = IWineD3DSurface_LockRect(iface,
2062 &lock,
2063 NULL,
2066 if(This->Flags & SFLAG_PBO) {
2067 /* Sync the DIB with the PBO. This can't be done earlier because LockRect activates the allocatedMemory */
2068 memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, This->dib.bitmap_size);
2071 if(FAILED(hr)) {
2072 ERR("IWineD3DSurface_LockRect failed with hr = %08x\n", hr);
2073 /* keep the dib section */
2074 return hr;
2077 if (This->resource.format_desc->format == WINED3DFMT_P8_UINT
2078 || This->resource.format_desc->format == WINED3DFMT_P8_UINT_A8_UNORM)
2080 /* GetDC on palettized formats is unsupported in D3D9, and the method is missing in
2081 D3D8, so this should only be used for DX <=7 surfaces (with non-device palettes) */
2082 unsigned int n;
2083 const PALETTEENTRY *pal = NULL;
2085 if(This->palette) {
2086 pal = This->palette->palents;
2087 } else {
2088 IWineD3DSurfaceImpl *dds_primary;
2089 IWineD3DSwapChainImpl *swapchain;
2090 swapchain = (IWineD3DSwapChainImpl *)This->resource.device->swapchains[0];
2091 dds_primary = swapchain->front_buffer;
2092 if (dds_primary && dds_primary->palette)
2093 pal = dds_primary->palette->palents;
2096 if (pal) {
2097 for (n=0; n<256; n++) {
2098 col[n].rgbRed = pal[n].peRed;
2099 col[n].rgbGreen = pal[n].peGreen;
2100 col[n].rgbBlue = pal[n].peBlue;
2101 col[n].rgbReserved = 0;
2103 SetDIBColorTable(This->hDC, 0, 256, col);
2107 *pHDC = This->hDC;
2108 TRACE("returning %p\n",*pHDC);
2109 This->Flags |= SFLAG_DCINUSE;
2111 return WINED3D_OK;
2114 static HRESULT WINAPI IWineD3DSurfaceImpl_ReleaseDC(IWineD3DSurface *iface, HDC hDC)
2116 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2118 TRACE("(%p)->(%p)\n",This,hDC);
2120 if (!(This->Flags & SFLAG_DCINUSE))
2121 return WINEDDERR_NODC;
2123 if (This->hDC !=hDC) {
2124 WARN("Application tries to release an invalid DC(%p), surface dc is %p\n", hDC, This->hDC);
2125 return WINEDDERR_NODC;
2128 if((This->Flags & SFLAG_PBO) && This->resource.allocatedMemory) {
2129 /* Copy the contents of the DIB over to the PBO */
2130 memcpy(This->resource.allocatedMemory, This->dib.bitmap_data, This->dib.bitmap_size);
2133 /* we locked first, so unlock now */
2134 IWineD3DSurface_UnlockRect(iface);
2136 This->Flags &= ~SFLAG_DCINUSE;
2138 return WINED3D_OK;
2141 /* ******************************************************
2142 IWineD3DSurface Internal (No mapping to directx api) parts follow
2143 ****************************************************** */
2145 HRESULT d3dfmt_get_conv(IWineD3DSurfaceImpl *This, BOOL need_alpha_ck, BOOL use_texturing, struct wined3d_format_desc *desc, CONVERT_TYPES *convert)
2147 BOOL colorkey_active = need_alpha_ck && (This->CKeyFlags & WINEDDSD_CKSRCBLT);
2148 IWineD3DDeviceImpl *device = This->resource.device;
2149 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2150 BOOL blit_supported = FALSE;
2152 /* Copy the default values from the surface. Below we might perform fixups */
2153 /* TODO: get rid of color keying desc fixups by using e.g. a table. */
2154 *desc = *This->resource.format_desc;
2155 *convert = NO_CONVERSION;
2157 /* Ok, now look if we have to do any conversion */
2158 switch(This->resource.format_desc->format)
2160 case WINED3DFMT_P8_UINT:
2161 /* ****************
2162 Paletted Texture
2163 **************** */
2165 /* Below the call to blit_supported is disabled for Wine 1.2 because the function isn't operating correctly yet.
2166 * At the moment 8-bit blits are handled in software and if certain GL extensions are around, surface conversion
2167 * is performed at upload time. The blit_supported call recognizes it as a destination fixup. This type of upload 'fixup'
2168 * and 8-bit to 8-bit blits need to be handled by the blit_shader.
2169 * TODO: get rid of this #if 0
2171 #if 0
2172 blit_supported = device->blitter->blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
2173 &rect, This->resource.usage, This->resource.pool,
2174 This->resource.format_desc, &rect, This->resource.usage,
2175 This->resource.pool, This->resource.format_desc);
2176 #endif
2177 blit_supported = gl_info->supported[EXT_PALETTED_TEXTURE] || gl_info->supported[ARB_FRAGMENT_PROGRAM];
2179 /* Use conversion when the blit_shader backend supports it. It only supports this in case of
2180 * texturing. Further also use conversion in case of color keying.
2181 * Paletted textures can be emulated using shaders but only do that for 2D purposes e.g. situations
2182 * in which the main render target uses p8. Some games like GTA Vice City use P8 for texturing which
2183 * conflicts with this.
2185 if (!((blit_supported && device->render_targets && This == device->render_targets[0]))
2186 || colorkey_active || !use_texturing)
2188 desc->glFormat = GL_RGBA;
2189 desc->glInternal = GL_RGBA;
2190 desc->glType = GL_UNSIGNED_BYTE;
2191 desc->conv_byte_count = 4;
2192 if(colorkey_active) {
2193 *convert = CONVERT_PALETTED_CK;
2194 } else {
2195 *convert = CONVERT_PALETTED;
2198 break;
2200 case WINED3DFMT_B2G3R3_UNORM:
2201 /* **********************
2202 GL_UNSIGNED_BYTE_3_3_2
2203 ********************** */
2204 if (colorkey_active) {
2205 /* This texture format will never be used.. So do not care about color keying
2206 up until the point in time it will be needed :-) */
2207 FIXME(" ColorKeying not supported in the RGB 332 format !\n");
2209 break;
2211 case WINED3DFMT_B5G6R5_UNORM:
2212 if (colorkey_active) {
2213 *convert = CONVERT_CK_565;
2214 desc->glFormat = GL_RGBA;
2215 desc->glInternal = GL_RGB5_A1;
2216 desc->glType = GL_UNSIGNED_SHORT_5_5_5_1;
2217 desc->conv_byte_count = 2;
2219 break;
2221 case WINED3DFMT_B5G5R5X1_UNORM:
2222 if (colorkey_active) {
2223 *convert = CONVERT_CK_5551;
2224 desc->glFormat = GL_BGRA;
2225 desc->glInternal = GL_RGB5_A1;
2226 desc->glType = GL_UNSIGNED_SHORT_1_5_5_5_REV;
2227 desc->conv_byte_count = 2;
2229 break;
2231 case WINED3DFMT_B8G8R8_UNORM:
2232 if (colorkey_active) {
2233 *convert = CONVERT_CK_RGB24;
2234 desc->glFormat = GL_RGBA;
2235 desc->glInternal = GL_RGBA8;
2236 desc->glType = GL_UNSIGNED_INT_8_8_8_8;
2237 desc->conv_byte_count = 4;
2239 break;
2241 case WINED3DFMT_B8G8R8X8_UNORM:
2242 if (colorkey_active) {
2243 *convert = CONVERT_RGB32_888;
2244 desc->glFormat = GL_RGBA;
2245 desc->glInternal = GL_RGBA8;
2246 desc->glType = GL_UNSIGNED_INT_8_8_8_8;
2247 desc->conv_byte_count = 4;
2249 break;
2251 default:
2252 break;
2255 return WINED3D_OK;
2258 void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey)
2260 IWineD3DDeviceImpl *device = This->resource.device;
2261 IWineD3DPaletteImpl *pal = This->palette;
2262 BOOL index_in_alpha = FALSE;
2263 unsigned int i;
2265 /* Old games like StarCraft, C&C, Red Alert and others use P8 render targets.
2266 * Reading back the RGB output each lockrect (each frame as they lock the whole screen)
2267 * is slow. Further RGB->P8 conversion is not possible because palettes can have
2268 * duplicate entries. Store the color key in the unused alpha component to speed the
2269 * download up and to make conversion unneeded. */
2270 index_in_alpha = primary_render_target_is_p8(device);
2272 if (!pal)
2274 UINT dxVersion = ((IWineD3DImpl *)device->wined3d)->dxVersion;
2276 /* In DirectDraw the palette is a property of the surface, there are no such things as device palettes. */
2277 if (dxVersion <= 7)
2279 ERR("This code should never get entered for DirectDraw!, expect problems\n");
2280 if (index_in_alpha)
2282 /* Guarantees that memory representation remains correct after sysmem<->texture transfers even if
2283 * there's no palette at this time. */
2284 for (i = 0; i < 256; i++) table[i][3] = i;
2287 else
2289 /* Direct3D >= 8 palette usage style: P8 textures use device palettes, palette entry format is A8R8G8B8,
2290 * alpha is stored in peFlags and may be used by the app if D3DPTEXTURECAPS_ALPHAPALETTE device
2291 * capability flag is present (wine does advertise this capability) */
2292 for (i = 0; i < 256; ++i)
2294 table[i][0] = device->palettes[device->currentPalette][i].peRed;
2295 table[i][1] = device->palettes[device->currentPalette][i].peGreen;
2296 table[i][2] = device->palettes[device->currentPalette][i].peBlue;
2297 table[i][3] = device->palettes[device->currentPalette][i].peFlags;
2301 else
2303 TRACE("Using surface palette %p\n", pal);
2304 /* Get the surface's palette */
2305 for (i = 0; i < 256; ++i)
2307 table[i][0] = pal->palents[i].peRed;
2308 table[i][1] = pal->palents[i].peGreen;
2309 table[i][2] = pal->palents[i].peBlue;
2311 /* When index_in_alpha is set the palette index is stored in the
2312 * alpha component. In case of a readback we can then read
2313 * GL_ALPHA. Color keying is handled in BltOverride using a
2314 * GL_ALPHA_TEST using GL_NOT_EQUAL. In case of index_in_alpha the
2315 * color key itself is passed to glAlphaFunc in other cases the
2316 * alpha component of pixels that should be masked away is set to 0. */
2317 if (index_in_alpha)
2319 table[i][3] = i;
2321 else if (colorkey && (i >= This->SrcBltCKey.dwColorSpaceLowValue)
2322 && (i <= This->SrcBltCKey.dwColorSpaceHighValue))
2324 table[i][3] = 0x00;
2326 else if(pal->Flags & WINEDDPCAPS_ALPHA)
2328 table[i][3] = pal->palents[i].peFlags;
2330 else
2332 table[i][3] = 0xFF;
2338 static HRESULT d3dfmt_convert_surface(const BYTE *src, BYTE *dst, UINT pitch, UINT width,
2339 UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *This)
2341 const BYTE *source;
2342 BYTE *dest;
2343 TRACE("(%p)->(%p),(%d,%d,%d,%d,%p)\n", src, dst, pitch, height, outpitch, convert,This);
2345 switch (convert) {
2346 case NO_CONVERSION:
2348 memcpy(dst, src, pitch * height);
2349 break;
2351 case CONVERT_PALETTED:
2352 case CONVERT_PALETTED_CK:
2354 IWineD3DPaletteImpl* pal = This->palette;
2355 BYTE table[256][4];
2356 unsigned int x, y;
2358 if( pal == NULL) {
2359 /* TODO: If we are a sublevel, try to get the palette from level 0 */
2362 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
2364 for (y = 0; y < height; y++)
2366 source = src + pitch * y;
2367 dest = dst + outpitch * y;
2368 /* This is an 1 bpp format, using the width here is fine */
2369 for (x = 0; x < width; x++) {
2370 BYTE color = *source++;
2371 *dest++ = table[color][0];
2372 *dest++ = table[color][1];
2373 *dest++ = table[color][2];
2374 *dest++ = table[color][3];
2378 break;
2380 case CONVERT_CK_565:
2382 /* Converting the 565 format in 5551 packed to emulate color-keying.
2384 Note : in all these conversion, it would be best to average the averaging
2385 pixels to get the color of the pixel that will be color-keyed to
2386 prevent 'color bleeding'. This will be done later on if ever it is
2387 too visible.
2389 Note2: Nvidia documents say that their driver does not support alpha + color keying
2390 on the same surface and disables color keying in such a case
2392 unsigned int x, y;
2393 const WORD *Source;
2394 WORD *Dest;
2396 TRACE("Color keyed 565\n");
2398 for (y = 0; y < height; y++) {
2399 Source = (const WORD *)(src + y * pitch);
2400 Dest = (WORD *) (dst + y * outpitch);
2401 for (x = 0; x < width; x++ ) {
2402 WORD color = *Source++;
2403 *Dest = ((color & 0xFFC0) | ((color & 0x1F) << 1));
2404 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2405 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2406 *Dest |= 0x0001;
2408 Dest++;
2412 break;
2414 case CONVERT_CK_5551:
2416 /* Converting X1R5G5B5 format to R5G5B5A1 to emulate color-keying. */
2417 unsigned int x, y;
2418 const WORD *Source;
2419 WORD *Dest;
2420 TRACE("Color keyed 5551\n");
2421 for (y = 0; y < height; y++) {
2422 Source = (const WORD *)(src + y * pitch);
2423 Dest = (WORD *) (dst + y * outpitch);
2424 for (x = 0; x < width; x++ ) {
2425 WORD color = *Source++;
2426 *Dest = color;
2427 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2428 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2429 *Dest |= (1 << 15);
2431 else {
2432 *Dest &= ~(1 << 15);
2434 Dest++;
2438 break;
2440 case CONVERT_CK_RGB24:
2442 /* Converting R8G8B8 format to R8G8B8A8 with color-keying. */
2443 unsigned int x, y;
2444 for (y = 0; y < height; y++)
2446 source = src + pitch * y;
2447 dest = dst + outpitch * y;
2448 for (x = 0; x < width; x++) {
2449 DWORD color = ((DWORD)source[0] << 16) + ((DWORD)source[1] << 8) + (DWORD)source[2] ;
2450 DWORD dstcolor = color << 8;
2451 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2452 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2453 dstcolor |= 0xff;
2455 *(DWORD*)dest = dstcolor;
2456 source += 3;
2457 dest += 4;
2461 break;
2463 case CONVERT_RGB32_888:
2465 /* Converting X8R8G8B8 format to R8G8B8A8 with color-keying. */
2466 unsigned int x, y;
2467 for (y = 0; y < height; y++)
2469 source = src + pitch * y;
2470 dest = dst + outpitch * y;
2471 for (x = 0; x < width; x++) {
2472 DWORD color = 0xffffff & *(const DWORD*)source;
2473 DWORD dstcolor = color << 8;
2474 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2475 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2476 dstcolor |= 0xff;
2478 *(DWORD*)dest = dstcolor;
2479 source += 4;
2480 dest += 4;
2484 break;
2486 default:
2487 ERR("Unsupported conversion type %#x.\n", convert);
2489 return WINED3D_OK;
2492 BOOL palette9_changed(IWineD3DSurfaceImpl *This)
2494 IWineD3DDeviceImpl *device = This->resource.device;
2496 if (This->palette || (This->resource.format_desc->format != WINED3DFMT_P8_UINT
2497 && This->resource.format_desc->format != WINED3DFMT_P8_UINT_A8_UNORM))
2499 /* If a ddraw-style palette is attached assume no d3d9 palette change.
2500 * Also the palette isn't interesting if the surface format isn't P8 or A8P8
2502 return FALSE;
2505 if (This->palette9)
2507 if (!memcmp(This->palette9, device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256))
2509 return FALSE;
2511 } else {
2512 This->palette9 = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
2514 memcpy(This->palette9, device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256);
2515 return TRUE;
2518 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadTexture(IWineD3DSurface *iface, BOOL srgb_mode) {
2519 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2520 DWORD flag = srgb_mode ? SFLAG_INSRGBTEX : SFLAG_INTEXTURE;
2522 if (!(This->Flags & flag)) {
2523 TRACE("Reloading because surface is dirty\n");
2524 } else if(/* Reload: gl texture has ck, now no ckey is set OR */
2525 ((This->Flags & SFLAG_GLCKEY) && (!(This->CKeyFlags & WINEDDSD_CKSRCBLT))) ||
2526 /* Reload: vice versa OR */
2527 ((!(This->Flags & SFLAG_GLCKEY)) && (This->CKeyFlags & WINEDDSD_CKSRCBLT)) ||
2528 /* Also reload: Color key is active AND the color key has changed */
2529 ((This->CKeyFlags & WINEDDSD_CKSRCBLT) && (
2530 (This->glCKey.dwColorSpaceLowValue != This->SrcBltCKey.dwColorSpaceLowValue) ||
2531 (This->glCKey.dwColorSpaceHighValue != This->SrcBltCKey.dwColorSpaceHighValue)))) {
2532 TRACE("Reloading because of color keying\n");
2533 /* To perform the color key conversion we need a sysmem copy of
2534 * the surface. Make sure we have it
2537 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
2538 /* Make sure the texture is reloaded because of the color key change, this kills performance though :( */
2539 /* TODO: This is not necessarily needed with hw palettized texture support */
2540 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2541 } else {
2542 TRACE("surface is already in texture\n");
2543 return WINED3D_OK;
2546 /* Resources are placed in system RAM and do not need to be recreated when a device is lost.
2547 * These resources are not bound by device size or format restrictions. Because of this,
2548 * these resources cannot be accessed by the Direct3D device nor set as textures or render targets.
2549 * However, these resources can always be created, locked, and copied.
2551 if (This->resource.pool == WINED3DPOOL_SCRATCH )
2553 FIXME("(%p) Operation not supported for scratch textures\n",This);
2554 return WINED3DERR_INVALIDCALL;
2557 IWineD3DSurface_LoadLocation(iface, flag, NULL /* no partial locking for textures yet */);
2559 if (!(This->Flags & SFLAG_DONOTFREE)) {
2560 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
2561 This->resource.allocatedMemory = NULL;
2562 This->resource.heapMemory = NULL;
2563 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, FALSE);
2566 return WINED3D_OK;
2569 /* Context activation is done by the caller. */
2570 static void WINAPI IWineD3DSurfaceImpl_BindTexture(IWineD3DSurface *iface, BOOL srgb) {
2571 /* TODO: check for locks */
2572 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2573 IWineD3DBaseTexture *baseTexture = NULL;
2575 TRACE("(%p)Checking to see if the container is a base texture\n", This);
2576 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
2577 TRACE("Passing to container\n");
2578 IWineD3DBaseTexture_BindTexture(baseTexture, srgb);
2579 IWineD3DBaseTexture_Release(baseTexture);
2581 else
2583 GLuint *name;
2585 TRACE("(%p) : Binding surface\n", This);
2587 name = srgb ? &This->texture_name_srgb : &This->texture_name;
2589 ENTER_GL();
2591 if (!This->texture_level)
2593 if (!*name) {
2594 glGenTextures(1, name);
2595 checkGLcall("glGenTextures");
2596 TRACE("Surface %p given name %d\n", This, *name);
2598 glBindTexture(This->texture_target, *name);
2599 checkGLcall("glBindTexture");
2600 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2601 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)");
2602 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2603 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)");
2604 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
2605 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)");
2606 glTexParameteri(This->texture_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2607 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_MIN_FILTER, GL_NEAREST)");
2608 glTexParameteri(This->texture_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2609 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_MAG_FILTER, GL_NEAREST)");
2611 /* This is where we should be reducing the amount of GLMemoryUsed */
2612 } else if (*name) {
2613 /* Mipmap surfaces should have a base texture container */
2614 ERR("Mipmap surface has a glTexture bound to it!\n");
2617 glBindTexture(This->texture_target, *name);
2618 checkGLcall("glBindTexture");
2620 LEAVE_GL();
2624 static HRESULT WINAPI IWineD3DSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format) {
2625 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2626 HRESULT hr;
2628 TRACE("(%p) : Calling base function first\n", This);
2629 hr = IWineD3DBaseSurfaceImpl_SetFormat(iface, format);
2630 if(SUCCEEDED(hr)) {
2631 This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
2632 TRACE("(%p) : glFormat %d, glFormatInternal %d, glType %d\n", This, This->resource.format_desc->glFormat,
2633 This->resource.format_desc->glInternal, This->resource.format_desc->glType);
2635 return hr;
2638 static HRESULT WINAPI IWineD3DSurfaceImpl_SetMem(IWineD3DSurface *iface, void *Mem) {
2639 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
2641 if(This->Flags & (SFLAG_LOCKED | SFLAG_DCINUSE)) {
2642 WARN("Surface is locked or the HDC is in use\n");
2643 return WINED3DERR_INVALIDCALL;
2646 if(Mem && Mem != This->resource.allocatedMemory) {
2647 void *release = NULL;
2649 /* Do I have to copy the old surface content? */
2650 if(This->Flags & SFLAG_DIBSECTION) {
2651 /* Release the DC. No need to hold the critical section for the update
2652 * Thread because this thread runs only on front buffers, but this method
2653 * fails for render targets in the check above.
2655 SelectObject(This->hDC, This->dib.holdbitmap);
2656 DeleteDC(This->hDC);
2657 /* Release the DIB section */
2658 DeleteObject(This->dib.DIBsection);
2659 This->dib.bitmap_data = NULL;
2660 This->resource.allocatedMemory = NULL;
2661 This->hDC = NULL;
2662 This->Flags &= ~SFLAG_DIBSECTION;
2663 } else if(!(This->Flags & SFLAG_USERPTR)) {
2664 release = This->resource.heapMemory;
2665 This->resource.heapMemory = NULL;
2667 This->resource.allocatedMemory = Mem;
2668 This->Flags |= SFLAG_USERPTR | SFLAG_INSYSMEM;
2670 /* Now the surface memory is most up do date. Invalidate drawable and texture */
2671 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2673 /* For client textures opengl has to be notified */
2674 if (This->Flags & SFLAG_CLIENT)
2675 surface_release_client_storage(This);
2677 /* Now free the old memory if any */
2678 HeapFree(GetProcessHeap(), 0, release);
2679 } else if(This->Flags & SFLAG_USERPTR) {
2680 /* LockRect and GetDC will re-create the dib section and allocated memory */
2681 This->resource.allocatedMemory = NULL;
2682 /* HeapMemory should be NULL already */
2683 if(This->resource.heapMemory != NULL) ERR("User pointer surface has heap memory allocated\n");
2684 This->Flags &= ~SFLAG_USERPTR;
2686 if (This->Flags & SFLAG_CLIENT)
2687 surface_release_client_storage(This);
2689 return WINED3D_OK;
2692 void flip_surface(IWineD3DSurfaceImpl *front, IWineD3DSurfaceImpl *back) {
2694 /* Flip the surface contents */
2695 /* Flip the DC */
2697 HDC tmp;
2698 tmp = front->hDC;
2699 front->hDC = back->hDC;
2700 back->hDC = tmp;
2703 /* Flip the DIBsection */
2705 HBITMAP tmp;
2706 BOOL hasDib = front->Flags & SFLAG_DIBSECTION;
2707 tmp = front->dib.DIBsection;
2708 front->dib.DIBsection = back->dib.DIBsection;
2709 back->dib.DIBsection = tmp;
2711 if(back->Flags & SFLAG_DIBSECTION) front->Flags |= SFLAG_DIBSECTION;
2712 else front->Flags &= ~SFLAG_DIBSECTION;
2713 if(hasDib) back->Flags |= SFLAG_DIBSECTION;
2714 else back->Flags &= ~SFLAG_DIBSECTION;
2717 /* Flip the surface data */
2719 void* tmp;
2721 tmp = front->dib.bitmap_data;
2722 front->dib.bitmap_data = back->dib.bitmap_data;
2723 back->dib.bitmap_data = tmp;
2725 tmp = front->resource.allocatedMemory;
2726 front->resource.allocatedMemory = back->resource.allocatedMemory;
2727 back->resource.allocatedMemory = tmp;
2729 tmp = front->resource.heapMemory;
2730 front->resource.heapMemory = back->resource.heapMemory;
2731 back->resource.heapMemory = tmp;
2734 /* Flip the PBO */
2736 GLuint tmp_pbo = front->pbo;
2737 front->pbo = back->pbo;
2738 back->pbo = tmp_pbo;
2741 /* client_memory should not be different, but just in case */
2743 BOOL tmp;
2744 tmp = front->dib.client_memory;
2745 front->dib.client_memory = back->dib.client_memory;
2746 back->dib.client_memory = tmp;
2749 /* Flip the opengl texture */
2751 GLuint tmp;
2753 tmp = back->texture_name;
2754 back->texture_name = front->texture_name;
2755 front->texture_name = tmp;
2757 tmp = back->texture_name_srgb;
2758 back->texture_name_srgb = front->texture_name_srgb;
2759 front->texture_name_srgb = tmp;
2763 DWORD tmp_flags = back->Flags;
2764 back->Flags = front->Flags;
2765 front->Flags = tmp_flags;
2769 static HRESULT WINAPI IWineD3DSurfaceImpl_Flip(IWineD3DSurface *iface, IWineD3DSurface *override, DWORD Flags) {
2770 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2771 IWineD3DSwapChainImpl *swapchain = NULL;
2772 HRESULT hr;
2773 TRACE("(%p)->(%p,%x)\n", This, override, Flags);
2775 /* Flipping is only supported on RenderTargets and overlays*/
2776 if( !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_OVERLAY)) ) {
2777 WARN("Tried to flip a non-render target, non-overlay surface\n");
2778 return WINEDDERR_NOTFLIPPABLE;
2781 if(This->resource.usage & WINED3DUSAGE_OVERLAY) {
2782 flip_surface(This, (IWineD3DSurfaceImpl *) override);
2784 /* Update the overlay if it is visible */
2785 if(This->overlay_dest) {
2786 return IWineD3DSurface_DrawOverlay((IWineD3DSurface *) This);
2787 } else {
2788 return WINED3D_OK;
2792 if(override) {
2793 /* DDraw sets this for the X11 surfaces, so don't confuse the user
2794 * FIXME("(%p) Target override is not supported by now\n", This);
2795 * Additionally, it isn't really possible to support triple-buffering
2796 * properly on opengl at all
2800 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **) &swapchain);
2801 if(!swapchain) {
2802 ERR("Flipped surface is not on a swapchain\n");
2803 return WINEDDERR_NOTFLIPPABLE;
2806 /* Just overwrite the swapchain presentation interval. This is ok because only ddraw apps can call Flip,
2807 * and only d3d8 and d3d9 apps specify the presentation interval
2809 if((Flags & (WINEDDFLIP_NOVSYNC | WINEDDFLIP_INTERVAL2 | WINEDDFLIP_INTERVAL3 | WINEDDFLIP_INTERVAL4)) == 0) {
2810 /* Most common case first to avoid wasting time on all the other cases */
2811 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_ONE;
2812 } else if(Flags & WINEDDFLIP_NOVSYNC) {
2813 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
2814 } else if(Flags & WINEDDFLIP_INTERVAL2) {
2815 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_TWO;
2816 } else if(Flags & WINEDDFLIP_INTERVAL3) {
2817 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_THREE;
2818 } else {
2819 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_FOUR;
2822 /* Flipping a OpenGL surface -> Use WineD3DDevice::Present */
2823 hr = IWineD3DSwapChain_Present((IWineD3DSwapChain *)swapchain,
2824 NULL, NULL, swapchain->win_handle, NULL, 0);
2825 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
2826 return hr;
2829 /* Does a direct frame buffer -> texture copy. Stretching is done
2830 * with single pixel copy calls
2832 static void fb_copy_to_texture_direct(IWineD3DSurfaceImpl *dst_surface, IWineD3DSurfaceImpl *src_surface,
2833 const RECT *src_rect, const RECT *dst_rect_in, WINED3DTEXTUREFILTERTYPE Filter)
2835 IWineD3DDeviceImpl *device = dst_surface->resource.device;
2836 float xrel, yrel;
2837 UINT row;
2838 struct wined3d_context *context;
2839 BOOL upsidedown = FALSE;
2840 RECT dst_rect = *dst_rect_in;
2842 /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
2843 * glCopyTexSubImage is a bit picky about the parameters we pass to it
2845 if(dst_rect.top > dst_rect.bottom) {
2846 UINT tmp = dst_rect.bottom;
2847 dst_rect.bottom = dst_rect.top;
2848 dst_rect.top = tmp;
2849 upsidedown = TRUE;
2852 context = context_acquire(device, src_surface);
2853 context_apply_blit_state(context, device);
2854 surface_internal_preload(dst_surface, SRGB_RGB);
2855 ENTER_GL();
2857 /* Bind the target texture */
2858 glBindTexture(dst_surface->texture_target, dst_surface->texture_name);
2859 checkGLcall("glBindTexture");
2860 if (surface_is_offscreen(src_surface))
2862 TRACE("Reading from an offscreen target\n");
2863 upsidedown = !upsidedown;
2864 glReadBuffer(device->offscreenBuffer);
2866 else
2868 glReadBuffer(surface_get_gl_buffer(src_surface));
2870 checkGLcall("glReadBuffer");
2872 xrel = (float) (src_rect->right - src_rect->left) / (float) (dst_rect.right - dst_rect.left);
2873 yrel = (float) (src_rect->bottom - src_rect->top) / (float) (dst_rect.bottom - dst_rect.top);
2875 if ((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
2877 FIXME("Doing a pixel by pixel copy from the framebuffer to a texture, expect major performance issues\n");
2879 if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
2880 ERR("Texture filtering not supported in direct blit\n");
2883 else if ((Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT)
2884 && ((yrel - 1.0f < -eps) || (yrel - 1.0f > eps)))
2886 ERR("Texture filtering not supported in direct blit\n");
2889 if (upsidedown
2890 && !((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
2891 && !((yrel - 1.0f < -eps) || (yrel - 1.0f > eps)))
2893 /* Upside down copy without stretching is nice, one glCopyTexSubImage call will do */
2895 glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
2896 dst_rect.left /*xoffset */, dst_rect.top /* y offset */,
2897 src_rect->left, src_surface->currentDesc.Height - src_rect->bottom,
2898 dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top);
2899 } else {
2900 UINT yoffset = src_surface->currentDesc.Height - src_rect->top + dst_rect.top - 1;
2901 /* I have to process this row by row to swap the image,
2902 * otherwise it would be upside down, so stretching in y direction
2903 * doesn't cost extra time
2905 * However, stretching in x direction can be avoided if not necessary
2907 for(row = dst_rect.top; row < dst_rect.bottom; row++) {
2908 if ((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
2910 /* Well, that stuff works, but it's very slow.
2911 * find a better way instead
2913 UINT col;
2915 for (col = dst_rect.left; col < dst_rect.right; ++col)
2917 glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
2918 dst_rect.left + col /* x offset */, row /* y offset */,
2919 src_rect->left + col * xrel, yoffset - (int) (row * yrel), 1, 1);
2922 else
2924 glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
2925 dst_rect.left /* x offset */, row /* y offset */,
2926 src_rect->left, yoffset - (int) (row * yrel), dst_rect.right - dst_rect.left, 1);
2930 checkGLcall("glCopyTexSubImage2D");
2932 LEAVE_GL();
2933 context_release(context);
2935 /* The texture is now most up to date - If the surface is a render target and has a drawable, this
2936 * path is never entered
2938 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)dst_surface, SFLAG_INTEXTURE, TRUE);
2941 /* Uses the hardware to stretch and flip the image */
2942 static void fb_copy_to_texture_hwstretch(IWineD3DSurfaceImpl *dst_surface, IWineD3DSurfaceImpl *src_surface,
2943 const RECT *src_rect, const RECT *dst_rect_in, WINED3DTEXTUREFILTERTYPE Filter)
2945 IWineD3DDeviceImpl *device = dst_surface->resource.device;
2946 GLuint src, backup = 0;
2947 IWineD3DSwapChainImpl *src_swapchain = NULL;
2948 float left, right, top, bottom; /* Texture coordinates */
2949 UINT fbwidth = src_surface->currentDesc.Width;
2950 UINT fbheight = src_surface->currentDesc.Height;
2951 struct wined3d_context *context;
2952 GLenum drawBuffer = GL_BACK;
2953 GLenum texture_target;
2954 BOOL noBackBufferBackup;
2955 BOOL src_offscreen;
2956 BOOL upsidedown = FALSE;
2957 RECT dst_rect = *dst_rect_in;
2959 TRACE("Using hwstretch blit\n");
2960 /* Activate the Proper context for reading from the source surface, set it up for blitting */
2961 context = context_acquire(device, src_surface);
2962 context_apply_blit_state(context, device);
2963 surface_internal_preload(dst_surface, SRGB_RGB);
2965 src_offscreen = surface_is_offscreen(src_surface);
2966 noBackBufferBackup = src_offscreen && wined3d_settings.offscreen_rendering_mode == ORM_FBO;
2967 if (!noBackBufferBackup && !src_surface->texture_name)
2969 /* Get it a description */
2970 surface_internal_preload(src_surface, SRGB_RGB);
2972 ENTER_GL();
2974 /* Try to use an aux buffer for drawing the rectangle. This way it doesn't need restoring.
2975 * This way we don't have to wait for the 2nd readback to finish to leave this function.
2977 if (context->aux_buffers >= 2)
2979 /* Got more than one aux buffer? Use the 2nd aux buffer */
2980 drawBuffer = GL_AUX1;
2982 else if ((!src_offscreen || device->offscreenBuffer == GL_BACK) && context->aux_buffers >= 1)
2984 /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
2985 drawBuffer = GL_AUX0;
2988 if(noBackBufferBackup) {
2989 glGenTextures(1, &backup);
2990 checkGLcall("glGenTextures");
2991 glBindTexture(GL_TEXTURE_2D, backup);
2992 checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
2993 texture_target = GL_TEXTURE_2D;
2994 } else {
2995 /* Backup the back buffer and copy the source buffer into a texture to draw an upside down stretched quad. If
2996 * we are reading from the back buffer, the backup can be used as source texture
2998 texture_target = src_surface->texture_target;
2999 glBindTexture(texture_target, src_surface->texture_name);
3000 checkGLcall("glBindTexture(texture_target, src_surface->texture_name)");
3001 glEnable(texture_target);
3002 checkGLcall("glEnable(texture_target)");
3004 /* For now invalidate the texture copy of the back buffer. Drawable and sysmem copy are untouched */
3005 src_surface->Flags &= ~SFLAG_INTEXTURE;
3008 /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
3009 * glCopyTexSubImage is a bit picky about the parameters we pass to it
3011 if(dst_rect.top > dst_rect.bottom) {
3012 UINT tmp = dst_rect.bottom;
3013 dst_rect.bottom = dst_rect.top;
3014 dst_rect.top = tmp;
3015 upsidedown = TRUE;
3018 if (src_offscreen)
3020 TRACE("Reading from an offscreen target\n");
3021 upsidedown = !upsidedown;
3022 glReadBuffer(device->offscreenBuffer);
3024 else
3026 glReadBuffer(surface_get_gl_buffer(src_surface));
3029 /* TODO: Only back up the part that will be overwritten */
3030 glCopyTexSubImage2D(texture_target, 0,
3031 0, 0 /* read offsets */,
3032 0, 0,
3033 fbwidth,
3034 fbheight);
3036 checkGLcall("glCopyTexSubImage2D");
3038 /* No issue with overriding these - the sampler is dirty due to blit usage */
3039 glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER,
3040 wined3d_gl_mag_filter(magLookup, Filter));
3041 checkGLcall("glTexParameteri");
3042 glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER,
3043 wined3d_gl_min_mip_filter(minMipLookup, Filter, WINED3DTEXF_NONE));
3044 checkGLcall("glTexParameteri");
3046 IWineD3DSurface_GetContainer((IWineD3DSurface *)src_surface, &IID_IWineD3DSwapChain, (void **)&src_swapchain);
3047 if (src_swapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *)src_swapchain);
3048 if (!src_swapchain || src_surface == src_swapchain->back_buffers[0])
3050 src = backup ? backup : src_surface->texture_name;
3052 else
3054 glReadBuffer(GL_FRONT);
3055 checkGLcall("glReadBuffer(GL_FRONT)");
3057 glGenTextures(1, &src);
3058 checkGLcall("glGenTextures(1, &src)");
3059 glBindTexture(GL_TEXTURE_2D, src);
3060 checkGLcall("glBindTexture(GL_TEXTURE_2D, src)");
3062 /* TODO: Only copy the part that will be read. Use src_rect->left, src_rect->bottom as origin, but with the width watch
3063 * out for power of 2 sizes
3065 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, src_surface->pow2Width,
3066 src_surface->pow2Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
3067 checkGLcall("glTexImage2D");
3068 glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
3069 0, 0 /* read offsets */,
3070 0, 0,
3071 fbwidth,
3072 fbheight);
3074 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
3075 checkGLcall("glTexParameteri");
3076 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
3077 checkGLcall("glTexParameteri");
3079 glReadBuffer(GL_BACK);
3080 checkGLcall("glReadBuffer(GL_BACK)");
3082 if(texture_target != GL_TEXTURE_2D) {
3083 glDisable(texture_target);
3084 glEnable(GL_TEXTURE_2D);
3085 texture_target = GL_TEXTURE_2D;
3088 checkGLcall("glEnd and previous");
3090 left = src_rect->left;
3091 right = src_rect->right;
3093 if (upsidedown)
3095 top = src_surface->currentDesc.Height - src_rect->top;
3096 bottom = src_surface->currentDesc.Height - src_rect->bottom;
3098 else
3100 top = src_surface->currentDesc.Height - src_rect->bottom;
3101 bottom = src_surface->currentDesc.Height - src_rect->top;
3104 if (src_surface->Flags & SFLAG_NORMCOORD)
3106 left /= src_surface->pow2Width;
3107 right /= src_surface->pow2Width;
3108 top /= src_surface->pow2Height;
3109 bottom /= src_surface->pow2Height;
3112 /* draw the source texture stretched and upside down. The correct surface is bound already */
3113 glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
3114 glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
3116 context_set_draw_buffer(context, drawBuffer);
3117 glReadBuffer(drawBuffer);
3119 glBegin(GL_QUADS);
3120 /* bottom left */
3121 glTexCoord2f(left, bottom);
3122 glVertex2i(0, fbheight);
3124 /* top left */
3125 glTexCoord2f(left, top);
3126 glVertex2i(0, fbheight - dst_rect.bottom - dst_rect.top);
3128 /* top right */
3129 glTexCoord2f(right, top);
3130 glVertex2i(dst_rect.right - dst_rect.left, fbheight - dst_rect.bottom - dst_rect.top);
3132 /* bottom right */
3133 glTexCoord2f(right, bottom);
3134 glVertex2i(dst_rect.right - dst_rect.left, fbheight);
3135 glEnd();
3136 checkGLcall("glEnd and previous");
3138 if (texture_target != dst_surface->texture_target)
3140 glDisable(texture_target);
3141 glEnable(dst_surface->texture_target);
3142 texture_target = dst_surface->texture_target;
3145 /* Now read the stretched and upside down image into the destination texture */
3146 glBindTexture(texture_target, dst_surface->texture_name);
3147 checkGLcall("glBindTexture");
3148 glCopyTexSubImage2D(texture_target,
3150 dst_rect.left, dst_rect.top, /* xoffset, yoffset */
3151 0, 0, /* We blitted the image to the origin */
3152 dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top);
3153 checkGLcall("glCopyTexSubImage2D");
3155 if(drawBuffer == GL_BACK) {
3156 /* Write the back buffer backup back */
3157 if(backup) {
3158 if(texture_target != GL_TEXTURE_2D) {
3159 glDisable(texture_target);
3160 glEnable(GL_TEXTURE_2D);
3161 texture_target = GL_TEXTURE_2D;
3163 glBindTexture(GL_TEXTURE_2D, backup);
3164 checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
3166 else
3168 if (texture_target != src_surface->texture_target)
3170 glDisable(texture_target);
3171 glEnable(src_surface->texture_target);
3172 texture_target = src_surface->texture_target;
3174 glBindTexture(src_surface->texture_target, src_surface->texture_name);
3175 checkGLcall("glBindTexture(src_surface->texture_target, src_surface->texture_name)");
3178 glBegin(GL_QUADS);
3179 /* top left */
3180 glTexCoord2f(0.0f, (float)fbheight / (float)src_surface->pow2Height);
3181 glVertex2i(0, 0);
3183 /* bottom left */
3184 glTexCoord2f(0.0f, 0.0f);
3185 glVertex2i(0, fbheight);
3187 /* bottom right */
3188 glTexCoord2f((float)fbwidth / (float)src_surface->pow2Width, 0.0f);
3189 glVertex2i(fbwidth, src_surface->currentDesc.Height);
3191 /* top right */
3192 glTexCoord2f((float)fbwidth / (float)src_surface->pow2Width,
3193 (float)fbheight / (float)src_surface->pow2Height);
3194 glVertex2i(fbwidth, 0);
3195 glEnd();
3197 glDisable(texture_target);
3198 checkGLcall("glDisable(texture_target)");
3200 /* Cleanup */
3201 if (src != src_surface->texture_name && src != backup)
3203 glDeleteTextures(1, &src);
3204 checkGLcall("glDeleteTextures(1, &src)");
3206 if(backup) {
3207 glDeleteTextures(1, &backup);
3208 checkGLcall("glDeleteTextures(1, &backup)");
3211 LEAVE_GL();
3213 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
3215 context_release(context);
3217 /* The texture is now most up to date - If the surface is a render target and has a drawable, this
3218 * path is never entered
3220 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)dst_surface, SFLAG_INTEXTURE, TRUE);
3223 /* Until the blit_shader is ready, define some prototypes here. */
3224 static BOOL fbo_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
3225 const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
3226 const struct wined3d_format_desc *src_format_desc,
3227 const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
3228 const struct wined3d_format_desc *dst_format_desc);
3230 /* Front buffer coordinates are always full screen coordinates, but our GL
3231 * drawable is limited to the window's client area. The sysmem and texture
3232 * copies do have the full screen size. Note that GL has a bottom-left
3233 * origin, while D3D has a top-left origin. */
3234 void surface_translate_frontbuffer_coords(IWineD3DSurfaceImpl *surface, HWND window, RECT *rect)
3236 POINT offset = {0, surface->currentDesc.Height};
3237 RECT windowsize;
3239 GetClientRect(window, &windowsize);
3240 offset.y -= windowsize.bottom - windowsize.top;
3241 ScreenToClient(window, &offset);
3242 OffsetRect(rect, offset.x, offset.y);
3245 /* Not called from the VTable */
3246 static HRESULT IWineD3DSurfaceImpl_BltOverride(IWineD3DSurfaceImpl *dst_surface, const RECT *DestRect,
3247 IWineD3DSurfaceImpl *src_surface, const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx,
3248 WINED3DTEXTUREFILTERTYPE Filter)
3250 IWineD3DDeviceImpl *device = dst_surface->resource.device;
3251 IWineD3DSwapChainImpl *srcSwapchain = NULL, *dstSwapchain = NULL;
3252 RECT dst_rect, src_rect;
3254 TRACE("dst_surface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, blt_fx %p, filter %s.\n",
3255 dst_surface, wine_dbgstr_rect(DestRect), src_surface, wine_dbgstr_rect(SrcRect),
3256 Flags, DDBltFx, debug_d3dtexturefiltertype(Filter));
3258 /* Get the swapchain. One of the surfaces has to be a primary surface */
3259 if (dst_surface->resource.pool == WINED3DPOOL_SYSTEMMEM)
3261 WARN("Destination is in sysmem, rejecting gl blt\n");
3262 return WINED3DERR_INVALIDCALL;
3264 IWineD3DSurface_GetContainer((IWineD3DSurface *)dst_surface, &IID_IWineD3DSwapChain, (void **)&dstSwapchain);
3265 if (dstSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *)dstSwapchain);
3266 if (src_surface)
3268 if (src_surface->resource.pool == WINED3DPOOL_SYSTEMMEM)
3270 WARN("Src is in sysmem, rejecting gl blt\n");
3271 return WINED3DERR_INVALIDCALL;
3273 IWineD3DSurface_GetContainer((IWineD3DSurface *)src_surface, &IID_IWineD3DSwapChain, (void **)&srcSwapchain);
3274 if (srcSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *)srcSwapchain);
3277 /* Early sort out of cases where no render target is used */
3278 if (!dstSwapchain && !srcSwapchain
3279 && src_surface != device->render_targets[0]
3280 && dst_surface != device->render_targets[0])
3282 TRACE("No surface is render target, not using hardware blit.\n");
3283 return WINED3DERR_INVALIDCALL;
3286 /* No destination color keying supported */
3287 if(Flags & (WINEDDBLT_KEYDEST | WINEDDBLT_KEYDESTOVERRIDE)) {
3288 /* Can we support that with glBlendFunc if blitting to the frame buffer? */
3289 TRACE("Destination color key not supported in accelerated Blit, falling back to software\n");
3290 return WINED3DERR_INVALIDCALL;
3293 surface_get_rect(dst_surface, DestRect, &dst_rect);
3294 if (src_surface) surface_get_rect(src_surface, SrcRect, &src_rect);
3296 /* The only case where both surfaces on a swapchain are supported is a back buffer -> front buffer blit on the same swapchain */
3297 if (dstSwapchain && dstSwapchain == srcSwapchain && dstSwapchain->back_buffers
3298 && dst_surface == dstSwapchain->front_buffer
3299 && src_surface == dstSwapchain->back_buffers[0])
3301 /* Half-life does a Blt from the back buffer to the front buffer,
3302 * Full surface size, no flags... Use present instead
3304 * This path will only be entered for d3d7 and ddraw apps, because d3d8/9 offer no way to blit TO the front buffer
3307 /* Check rects - IWineD3DDevice_Present doesn't handle them */
3308 while(1)
3310 TRACE("Looking if a Present can be done...\n");
3311 /* Source Rectangle must be full surface */
3312 if (src_rect.left || src_rect.top
3313 || src_rect.right != src_surface->currentDesc.Width
3314 || src_rect.bottom != src_surface->currentDesc.Height)
3316 TRACE("No, Source rectangle doesn't match\n");
3317 break;
3320 /* No stretching may occur */
3321 if(src_rect.right != dst_rect.right - dst_rect.left ||
3322 src_rect.bottom != dst_rect.bottom - dst_rect.top) {
3323 TRACE("No, stretching is done\n");
3324 break;
3327 /* Destination must be full surface or match the clipping rectangle */
3328 if (dst_surface->clipper && ((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd)
3330 RECT cliprect;
3331 POINT pos[2];
3332 GetClientRect(((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd, &cliprect);
3333 pos[0].x = dst_rect.left;
3334 pos[0].y = dst_rect.top;
3335 pos[1].x = dst_rect.right;
3336 pos[1].y = dst_rect.bottom;
3337 MapWindowPoints(GetDesktopWindow(), ((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd, pos, 2);
3339 if(pos[0].x != cliprect.left || pos[0].y != cliprect.top ||
3340 pos[1].x != cliprect.right || pos[1].y != cliprect.bottom)
3342 TRACE("No, dest rectangle doesn't match(clipper)\n");
3343 TRACE("Clip rect at %s\n", wine_dbgstr_rect(&cliprect));
3344 TRACE("Blt dest: %s\n", wine_dbgstr_rect(&dst_rect));
3345 break;
3348 else if (dst_rect.left || dst_rect.top
3349 || dst_rect.right != dst_surface->currentDesc.Width
3350 || dst_rect.bottom != dst_surface->currentDesc.Height)
3352 TRACE("No, dest rectangle doesn't match(surface size)\n");
3353 break;
3356 TRACE("Yes\n");
3358 /* These flags are unimportant for the flag check, remove them */
3359 if((Flags & ~(WINEDDBLT_DONOTWAIT | WINEDDBLT_WAIT)) == 0) {
3360 WINED3DSWAPEFFECT orig_swap = dstSwapchain->presentParms.SwapEffect;
3362 /* The idea behind this is that a glReadPixels and a glDrawPixels call
3363 * take very long, while a flip is fast.
3364 * This applies to Half-Life, which does such Blts every time it finished
3365 * a frame, and to Prince of Persia 3D, which uses this to draw at least the main
3366 * menu. This is also used by all apps when they do windowed rendering
3368 * The problem is that flipping is not really the same as copying. After a
3369 * Blt the front buffer is a copy of the back buffer, and the back buffer is
3370 * untouched. Therefore it's necessary to override the swap effect
3371 * and to set it back after the flip.
3373 * Windowed Direct3D < 7 apps do the same. The D3D7 sdk demos are nice
3374 * testcases.
3377 dstSwapchain->presentParms.SwapEffect = WINED3DSWAPEFFECT_COPY;
3378 dstSwapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
3380 TRACE("Full screen back buffer -> front buffer blt, performing a flip instead\n");
3381 IWineD3DSwapChain_Present((IWineD3DSwapChain *)dstSwapchain,
3382 NULL, NULL, dstSwapchain->win_handle, NULL, 0);
3384 dstSwapchain->presentParms.SwapEffect = orig_swap;
3386 return WINED3D_OK;
3388 break;
3391 TRACE("Unsupported blit between buffers on the same swapchain\n");
3392 return WINED3DERR_INVALIDCALL;
3393 } else if(dstSwapchain && dstSwapchain == srcSwapchain) {
3394 FIXME("Implement hardware blit between two surfaces on the same swapchain\n");
3395 return WINED3DERR_INVALIDCALL;
3396 } else if(dstSwapchain && srcSwapchain) {
3397 FIXME("Implement hardware blit between two different swapchains\n");
3398 return WINED3DERR_INVALIDCALL;
3400 else if (dstSwapchain)
3402 /* Handled with regular texture -> swapchain blit */
3403 if (src_surface == device->render_targets[0])
3404 TRACE("Blit from active render target to a swapchain\n");
3406 else if (srcSwapchain && dst_surface == device->render_targets[0])
3408 FIXME("Implement blit from a swapchain to the active render target\n");
3409 return WINED3DERR_INVALIDCALL;
3412 if ((srcSwapchain || src_surface == device->render_targets[0]) && !dstSwapchain)
3414 /* Blit from render target to texture */
3415 BOOL stretchx;
3417 /* P8 read back is not implemented */
3418 if (src_surface->resource.format_desc->format == WINED3DFMT_P8_UINT
3419 || dst_surface->resource.format_desc->format == WINED3DFMT_P8_UINT)
3421 TRACE("P8 read back not supported by frame buffer to texture blit\n");
3422 return WINED3DERR_INVALIDCALL;
3425 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3426 TRACE("Color keying not supported by frame buffer to texture blit\n");
3427 return WINED3DERR_INVALIDCALL;
3428 /* Destination color key is checked above */
3431 if(dst_rect.right - dst_rect.left != src_rect.right - src_rect.left) {
3432 stretchx = TRUE;
3433 } else {
3434 stretchx = FALSE;
3437 /* Blt is a pretty powerful call, while glCopyTexSubImage2D is not. glCopyTexSubImage cannot
3438 * flip the image nor scale it.
3440 * -> If the app asks for a unscaled, upside down copy, just perform one glCopyTexSubImage2D call
3441 * -> If the app wants a image width an unscaled width, copy it line per line
3442 * -> If the app wants a image that is scaled on the x axis, and the destination rectangle is smaller
3443 * than the frame buffer, draw an upside down scaled image onto the fb, read it back and restore the
3444 * back buffer. This is slower than reading line per line, thus not used for flipping
3445 * -> If the app wants a scaled image with a dest rect that is bigger than the fb, it has to be copied
3446 * pixel by pixel
3448 * If EXT_framebuffer_blit is supported that can be used instead. Note that EXT_framebuffer_blit implies
3449 * FBO support, so it doesn't really make sense to try and make it work with different offscreen rendering
3450 * backends.
3452 if (fbo_blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
3453 &src_rect, src_surface->resource.usage, src_surface->resource.pool, src_surface->resource.format_desc,
3454 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool, dst_surface->resource.format_desc))
3456 stretch_rect_fbo(device, src_surface, &src_rect, dst_surface, &dst_rect, Filter);
3458 else if (!stretchx || dst_rect.right - dst_rect.left > src_surface->currentDesc.Width
3459 || dst_rect.bottom - dst_rect.top > src_surface->currentDesc.Height)
3461 TRACE("No stretching in x direction, using direct framebuffer -> texture copy\n");
3462 fb_copy_to_texture_direct(dst_surface, src_surface, &src_rect, &dst_rect, Filter);
3463 } else {
3464 TRACE("Using hardware stretching to flip / stretch the texture\n");
3465 fb_copy_to_texture_hwstretch(dst_surface, src_surface, &src_rect, &dst_rect, Filter);
3468 if (!(dst_surface->Flags & SFLAG_DONOTFREE))
3470 HeapFree(GetProcessHeap(), 0, dst_surface->resource.heapMemory);
3471 dst_surface->resource.allocatedMemory = NULL;
3472 dst_surface->resource.heapMemory = NULL;
3474 else
3476 dst_surface->Flags &= ~SFLAG_INSYSMEM;
3479 return WINED3D_OK;
3481 else if (src_surface)
3483 /* Blit from offscreen surface to render target */
3484 DWORD oldCKeyFlags = src_surface->CKeyFlags;
3485 WINEDDCOLORKEY oldBltCKey = src_surface->SrcBltCKey;
3486 struct wined3d_context *context;
3488 TRACE("Blt from surface %p to rendertarget %p\n", src_surface, dst_surface);
3490 if (!(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE))
3491 && fbo_blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
3492 &src_rect, src_surface->resource.usage, src_surface->resource.pool,
3493 src_surface->resource.format_desc,
3494 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3495 dst_surface->resource.format_desc))
3497 TRACE("Using stretch_rect_fbo\n");
3498 /* The source is always a texture, but never the currently active render target, and the texture
3499 * contents are never upside down. */
3500 stretch_rect_fbo(device, src_surface, &src_rect, dst_surface, &dst_rect, Filter);
3501 return WINED3D_OK;
3504 if (!(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE))
3505 && arbfp_blit.blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
3506 &src_rect, src_surface->resource.usage, src_surface->resource.pool,
3507 src_surface->resource.format_desc,
3508 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3509 dst_surface->resource.format_desc))
3511 return arbfp_blit_surface(device, src_surface, &src_rect, dst_surface, &dst_rect, BLIT_OP_BLIT, Filter);
3514 /* Color keying: Check if we have to do a color keyed blt,
3515 * and if not check if a color key is activated.
3517 * Just modify the color keying parameters in the surface and restore them afterwards
3518 * The surface keeps track of the color key last used to load the opengl surface.
3519 * PreLoad will catch the change to the flags and color key and reload if necessary.
3521 if(Flags & WINEDDBLT_KEYSRC) {
3522 /* Use color key from surface */
3523 } else if(Flags & WINEDDBLT_KEYSRCOVERRIDE) {
3524 /* Use color key from DDBltFx */
3525 src_surface->CKeyFlags |= WINEDDSD_CKSRCBLT;
3526 src_surface->SrcBltCKey = DDBltFx->ddckSrcColorkey;
3527 } else {
3528 /* Do not use color key */
3529 src_surface->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
3532 /* Now load the surface */
3533 surface_internal_preload(src_surface, SRGB_RGB);
3535 /* Activate the destination context, set it up for blitting */
3536 context = context_acquire(device, dst_surface);
3537 context_apply_blit_state(context, device);
3539 if (dstSwapchain && dst_surface == dstSwapchain->front_buffer)
3540 surface_translate_frontbuffer_coords(dst_surface, context->win_handle, &dst_rect);
3542 if (!device->blitter->blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
3543 &src_rect, src_surface->resource.usage, src_surface->resource.pool, src_surface->resource.format_desc,
3544 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool, dst_surface->resource.format_desc))
3546 FIXME("Unsupported blit operation falling back to software\n");
3547 return WINED3DERR_INVALIDCALL;
3550 device->blitter->set_shader((IWineD3DDevice *)device, src_surface);
3552 ENTER_GL();
3554 /* This is for color keying */
3555 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3556 glEnable(GL_ALPHA_TEST);
3557 checkGLcall("glEnable(GL_ALPHA_TEST)");
3559 /* When the primary render target uses P8, the alpha component contains the palette index.
3560 * Which means that the colorkey is one of the palette entries. In other cases pixels that
3561 * should be masked away have alpha set to 0. */
3562 if (primary_render_target_is_p8(device))
3563 glAlphaFunc(GL_NOTEQUAL, (float)src_surface->SrcBltCKey.dwColorSpaceLowValue / 256.0f);
3564 else
3565 glAlphaFunc(GL_NOTEQUAL, 0.0f);
3566 checkGLcall("glAlphaFunc");
3567 } else {
3568 glDisable(GL_ALPHA_TEST);
3569 checkGLcall("glDisable(GL_ALPHA_TEST)");
3572 /* Draw a textured quad
3574 draw_textured_quad(src_surface, &src_rect, &dst_rect, Filter);
3576 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3577 glDisable(GL_ALPHA_TEST);
3578 checkGLcall("glDisable(GL_ALPHA_TEST)");
3581 /* Restore the color key parameters */
3582 src_surface->CKeyFlags = oldCKeyFlags;
3583 src_surface->SrcBltCKey = oldBltCKey;
3585 LEAVE_GL();
3587 /* Leave the opengl state valid for blitting */
3588 device->blitter->unset_shader((IWineD3DDevice *)device);
3590 if (wined3d_settings.strict_draw_ordering || (dstSwapchain
3591 && (dst_surface == dstSwapchain->front_buffer
3592 || dstSwapchain->num_contexts > 1)))
3593 wglFlush(); /* Flush to ensure ordering across contexts. */
3595 context_release(context);
3597 /* TODO: If the surface is locked often, perform the Blt in software on the memory instead */
3598 /* The surface is now in the drawable. On onscreen surfaces or without fbos the texture
3599 * is outdated now
3601 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)dst_surface, SFLAG_INDRAWABLE, TRUE);
3603 return WINED3D_OK;
3604 } else {
3605 /* Source-Less Blit to render target */
3606 if (Flags & WINEDDBLT_COLORFILL) {
3607 DWORD color;
3609 TRACE("Colorfill\n");
3611 /* The color as given in the Blt function is in the format of the frame-buffer...
3612 * 'clear' expect it in ARGB format => we need to do some conversion :-)
3614 if (!surface_convert_color_to_argb(dst_surface, DDBltFx->u5.dwFillColor, &color))
3616 /* The color conversion function already prints an error, so need to do it here */
3617 return WINED3DERR_INVALIDCALL;
3620 if (ffp_blit.blit_supported(&device->adapter->gl_info, BLIT_OP_COLOR_FILL,
3621 NULL, 0, 0, NULL,
3622 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3623 dst_surface->resource.format_desc))
3625 return ffp_blit.color_fill(device, dst_surface, &dst_rect, color);
3627 else if (cpu_blit.blit_supported(&device->adapter->gl_info, BLIT_OP_COLOR_FILL,
3628 NULL, 0, 0, NULL,
3629 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3630 dst_surface->resource.format_desc))
3632 return cpu_blit.color_fill(device, dst_surface, &dst_rect, color);
3634 return WINED3DERR_INVALIDCALL;
3638 /* Default: Fall back to the generic blt. Not an error, a TRACE is enough */
3639 TRACE("Didn't find any usable render target setup for hw blit, falling back to software\n");
3640 return WINED3DERR_INVALIDCALL;
3643 static HRESULT IWineD3DSurfaceImpl_BltZ(IWineD3DSurfaceImpl *This, const RECT *DestRect,
3644 IWineD3DSurface *SrcSurface, const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx)
3646 IWineD3DDeviceImpl *device = This->resource.device;
3647 float depth;
3649 if (Flags & WINEDDBLT_DEPTHFILL) {
3650 switch(This->resource.format_desc->format)
3652 case WINED3DFMT_D16_UNORM:
3653 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000ffff;
3654 break;
3655 case WINED3DFMT_S1_UINT_D15_UNORM:
3656 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000fffe;
3657 break;
3658 case WINED3DFMT_D24_UNORM_S8_UINT:
3659 case WINED3DFMT_X8D24_UNORM:
3660 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00ffffff;
3661 break;
3662 case WINED3DFMT_D32_UNORM:
3663 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0xffffffff;
3664 break;
3665 default:
3666 depth = 0.0f;
3667 ERR("Unexpected format for depth fill: %s\n", debug_d3dformat(This->resource.format_desc->format));
3670 return IWineD3DDevice_Clear((IWineD3DDevice *)device, DestRect ? 1 : 0, (const WINED3DRECT *)DestRect,
3671 WINED3DCLEAR_ZBUFFER, 0x00000000, depth, 0x00000000);
3674 FIXME("(%p): Unsupp depthstencil blit\n", This);
3675 return WINED3DERR_INVALIDCALL;
3678 static HRESULT WINAPI IWineD3DSurfaceImpl_Blt(IWineD3DSurface *iface, const RECT *DestRect, IWineD3DSurface *SrcSurface,
3679 const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
3680 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3681 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
3682 IWineD3DDeviceImpl *device = This->resource.device;
3684 TRACE("(%p)->(%p,%p,%p,%x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3685 TRACE("(%p): Usage is %s\n", This, debug_d3dusage(This->resource.usage));
3687 if ( (This->Flags & SFLAG_LOCKED) || ((Src != NULL) && (Src->Flags & SFLAG_LOCKED)))
3689 WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3690 return WINEDDERR_SURFACEBUSY;
3693 /* Accessing the depth stencil is supposed to fail between a BeginScene and EndScene pair,
3694 * except depth blits, which seem to work
3696 if (This == device->depth_stencil || (Src && Src == device->depth_stencil))
3698 if (device->inScene && !(Flags & WINEDDBLT_DEPTHFILL))
3700 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3701 return WINED3DERR_INVALIDCALL;
3702 } else if(IWineD3DSurfaceImpl_BltZ(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx) == WINED3D_OK) {
3703 TRACE("Z Blit override handled the blit\n");
3704 return WINED3D_OK;
3708 /* Special cases for RenderTargets */
3709 if ((This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3710 || (Src && (Src->resource.usage & WINED3DUSAGE_RENDERTARGET)))
3712 if (SUCCEEDED(IWineD3DSurfaceImpl_BltOverride(This, DestRect, Src, SrcRect, Flags, DDBltFx, Filter)))
3713 return WINED3D_OK;
3716 /* For the rest call the X11 surface implementation.
3717 * For RenderTargets this should be implemented OpenGL accelerated in BltOverride,
3718 * other Blts are rather rare
3720 return IWineD3DBaseSurfaceImpl_Blt(iface, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter);
3723 static HRESULT WINAPI IWineD3DSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty,
3724 IWineD3DSurface *Source, const RECT *rsrc, DWORD trans)
3726 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3727 IWineD3DSurfaceImpl *srcImpl = (IWineD3DSurfaceImpl *) Source;
3728 IWineD3DDeviceImpl *device = This->resource.device;
3730 TRACE("(%p)->(%d, %d, %p, %p, %08x\n", iface, dstx, dsty, Source, rsrc, trans);
3732 if ( (This->Flags & SFLAG_LOCKED) || (srcImpl->Flags & SFLAG_LOCKED))
3734 WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3735 return WINEDDERR_SURFACEBUSY;
3738 if (device->inScene && (This == device->depth_stencil || srcImpl == device->depth_stencil))
3740 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3741 return WINED3DERR_INVALIDCALL;
3744 /* Special cases for RenderTargets */
3745 if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3746 (srcImpl->resource.usage & WINED3DUSAGE_RENDERTARGET) ) {
3748 RECT SrcRect, DstRect;
3749 DWORD Flags=0;
3751 surface_get_rect(srcImpl, rsrc, &SrcRect);
3753 DstRect.left = dstx;
3754 DstRect.top=dsty;
3755 DstRect.right = dstx + SrcRect.right - SrcRect.left;
3756 DstRect.bottom = dsty + SrcRect.bottom - SrcRect.top;
3758 /* Convert BltFast flags into Btl ones because it is called from SurfaceImpl_Blt as well */
3759 if(trans & WINEDDBLTFAST_SRCCOLORKEY)
3760 Flags |= WINEDDBLT_KEYSRC;
3761 if(trans & WINEDDBLTFAST_DESTCOLORKEY)
3762 Flags |= WINEDDBLT_KEYDEST;
3763 if(trans & WINEDDBLTFAST_WAIT)
3764 Flags |= WINEDDBLT_WAIT;
3765 if(trans & WINEDDBLTFAST_DONOTWAIT)
3766 Flags |= WINEDDBLT_DONOTWAIT;
3768 if (SUCCEEDED(IWineD3DSurfaceImpl_BltOverride(This,
3769 &DstRect, srcImpl, &SrcRect, Flags, NULL, WINED3DTEXF_POINT)))
3770 return WINED3D_OK;
3774 return IWineD3DBaseSurfaceImpl_BltFast(iface, dstx, dsty, Source, rsrc, trans);
3777 static HRESULT WINAPI IWineD3DSurfaceImpl_RealizePalette(IWineD3DSurface *iface)
3779 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3780 RGBQUAD col[256];
3781 IWineD3DPaletteImpl *pal = This->palette;
3782 unsigned int n;
3783 TRACE("(%p)\n", This);
3785 if (!pal) return WINED3D_OK;
3787 if (This->resource.format_desc->format == WINED3DFMT_P8_UINT
3788 || This->resource.format_desc->format == WINED3DFMT_P8_UINT_A8_UNORM)
3790 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3792 /* Make sure the texture is up to date. This call doesn't do anything if the texture is already up to date. */
3793 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL);
3795 /* We want to force a palette refresh, so mark the drawable as not being up to date */
3796 IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, FALSE);
3797 } else {
3798 if(!(This->Flags & SFLAG_INSYSMEM)) {
3799 TRACE("Palette changed with surface that does not have an up to date system memory copy\n");
3800 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
3802 TRACE("Dirtifying surface\n");
3803 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
3807 if(This->Flags & SFLAG_DIBSECTION) {
3808 TRACE("(%p): Updating the hdc's palette\n", This);
3809 for (n=0; n<256; n++) {
3810 col[n].rgbRed = pal->palents[n].peRed;
3811 col[n].rgbGreen = pal->palents[n].peGreen;
3812 col[n].rgbBlue = pal->palents[n].peBlue;
3813 col[n].rgbReserved = 0;
3815 SetDIBColorTable(This->hDC, 0, 256, col);
3818 /* Propagate the changes to the drawable when we have a palette. */
3819 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3820 IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, NULL);
3822 return WINED3D_OK;
3825 static HRESULT WINAPI IWineD3DSurfaceImpl_PrivateSetup(IWineD3DSurface *iface) {
3826 /** Check against the maximum texture sizes supported by the video card **/
3827 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3828 const struct wined3d_gl_info *gl_info = &This->resource.device->adapter->gl_info;
3829 unsigned int pow2Width, pow2Height;
3831 This->texture_name = 0;
3832 This->texture_target = GL_TEXTURE_2D;
3834 /* Non-power2 support */
3835 if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] || gl_info->supported[WINE_NORMALIZED_TEXRECT])
3837 pow2Width = This->currentDesc.Width;
3838 pow2Height = This->currentDesc.Height;
3840 else
3842 /* Find the nearest pow2 match */
3843 pow2Width = pow2Height = 1;
3844 while (pow2Width < This->currentDesc.Width) pow2Width <<= 1;
3845 while (pow2Height < This->currentDesc.Height) pow2Height <<= 1;
3847 This->pow2Width = pow2Width;
3848 This->pow2Height = pow2Height;
3850 if (pow2Width > This->currentDesc.Width || pow2Height > This->currentDesc.Height) {
3851 /** TODO: add support for non power two compressed textures **/
3852 if (This->resource.format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
3854 FIXME("(%p) Compressed non-power-two textures are not supported w(%d) h(%d)\n",
3855 This, This->currentDesc.Width, This->currentDesc.Height);
3856 return WINED3DERR_NOTAVAILABLE;
3860 if(pow2Width != This->currentDesc.Width ||
3861 pow2Height != This->currentDesc.Height) {
3862 This->Flags |= SFLAG_NONPOW2;
3865 TRACE("%p\n", This);
3866 if ((This->pow2Width > gl_info->limits.texture_size || This->pow2Height > gl_info->limits.texture_size)
3867 && !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL)))
3869 /* one of three options
3870 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)
3871 2: Set the texture to the maximum size (bad idea)
3872 3: WARN and return WINED3DERR_NOTAVAILABLE;
3873 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.
3875 if(This->resource.pool == WINED3DPOOL_DEFAULT || This->resource.pool == WINED3DPOOL_MANAGED)
3877 WARN("(%p) Unable to allocate a surface which exceeds the maximum OpenGL texture size\n", This);
3878 return WINED3DERR_NOTAVAILABLE;
3881 /* We should never use this surface in combination with OpenGL! */
3882 TRACE("(%p) Creating an oversized surface: %ux%u\n", This, This->pow2Width, This->pow2Height);
3884 else
3886 /* Don't use ARB_TEXTURE_RECTANGLE in case the surface format is P8 and EXT_PALETTED_TEXTURE
3887 is used in combination with texture uploads (RTL_READTEX/RTL_TEXTEX). The reason is that EXT_PALETTED_TEXTURE
3888 doesn't work in combination with ARB_TEXTURE_RECTANGLE.
3890 if (This->Flags & SFLAG_NONPOW2 && gl_info->supported[ARB_TEXTURE_RECTANGLE]
3891 && !(This->resource.format_desc->format == WINED3DFMT_P8_UINT
3892 && gl_info->supported[EXT_PALETTED_TEXTURE]
3893 && wined3d_settings.rendertargetlock_mode == RTL_READTEX))
3895 This->texture_target = GL_TEXTURE_RECTANGLE_ARB;
3896 This->pow2Width = This->currentDesc.Width;
3897 This->pow2Height = This->currentDesc.Height;
3898 This->Flags &= ~(SFLAG_NONPOW2 | SFLAG_NORMCOORD);
3902 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
3903 switch(wined3d_settings.offscreen_rendering_mode) {
3904 case ORM_FBO: This->get_drawable_size = get_drawable_size_fbo; break;
3905 case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
3909 This->Flags |= SFLAG_INSYSMEM;
3911 return WINED3D_OK;
3914 /* GL locking is done by the caller */
3915 static void surface_depth_blt(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
3916 GLuint texture, GLsizei w, GLsizei h, GLenum target)
3918 IWineD3DDeviceImpl *device = This->resource.device;
3919 GLint compare_mode = GL_NONE;
3920 struct blt_info info;
3921 GLint old_binding = 0;
3923 glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_VIEWPORT_BIT);
3925 glDisable(GL_CULL_FACE);
3926 glDisable(GL_BLEND);
3927 glDisable(GL_ALPHA_TEST);
3928 glDisable(GL_SCISSOR_TEST);
3929 glDisable(GL_STENCIL_TEST);
3930 glEnable(GL_DEPTH_TEST);
3931 glDepthFunc(GL_ALWAYS);
3932 glDepthMask(GL_TRUE);
3933 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
3934 glViewport(0, 0, w, h);
3936 surface_get_blt_info(target, NULL, w, h, &info);
3937 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
3938 glGetIntegerv(info.binding, &old_binding);
3939 glBindTexture(info.bind_target, texture);
3940 if (gl_info->supported[ARB_SHADOW])
3942 glGetTexParameteriv(info.bind_target, GL_TEXTURE_COMPARE_MODE_ARB, &compare_mode);
3943 if (compare_mode != GL_NONE) glTexParameteri(info.bind_target, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE);
3946 device->shader_backend->shader_select_depth_blt((IWineD3DDevice *)device,
3947 info.tex_type, &This->ds_current_size);
3949 glBegin(GL_TRIANGLE_STRIP);
3950 glTexCoord3fv(info.coords[0]);
3951 glVertex2f(-1.0f, -1.0f);
3952 glTexCoord3fv(info.coords[1]);
3953 glVertex2f(1.0f, -1.0f);
3954 glTexCoord3fv(info.coords[2]);
3955 glVertex2f(-1.0f, 1.0f);
3956 glTexCoord3fv(info.coords[3]);
3957 glVertex2f(1.0f, 1.0f);
3958 glEnd();
3960 if (compare_mode != GL_NONE) glTexParameteri(info.bind_target, GL_TEXTURE_COMPARE_MODE_ARB, compare_mode);
3961 glBindTexture(info.bind_target, old_binding);
3963 glPopAttrib();
3965 device->shader_backend->shader_deselect_depth_blt((IWineD3DDevice *)device);
3968 void surface_modify_ds_location(IWineD3DSurfaceImpl *surface,
3969 DWORD location, UINT w, UINT h)
3971 TRACE("surface %p, new location %#x, w %u, h %u.\n", surface, location, w, h);
3973 if (location & ~SFLAG_DS_LOCATIONS)
3974 FIXME("Invalid location (%#x) specified.\n", location);
3976 surface->ds_current_size.cx = w;
3977 surface->ds_current_size.cy = h;
3978 surface->Flags &= ~SFLAG_DS_LOCATIONS;
3979 surface->Flags |= location;
3982 /* Context activation is done by the caller. */
3983 void surface_load_ds_location(IWineD3DSurfaceImpl *surface, struct wined3d_context *context, DWORD location)
3985 IWineD3DDeviceImpl *device = surface->resource.device;
3986 const struct wined3d_gl_info *gl_info = context->gl_info;
3988 TRACE("surface %p, new location %#x.\n", surface, location);
3990 /* TODO: Make this work for modes other than FBO */
3991 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return;
3993 if (!(surface->Flags & location))
3995 surface->ds_current_size.cx = 0;
3996 surface->ds_current_size.cy = 0;
3999 if (surface->ds_current_size.cx == surface->currentDesc.Width
4000 && surface->ds_current_size.cy == surface->currentDesc.Height)
4002 TRACE("Location (%#x) is already up to date.\n", location);
4003 return;
4006 if (surface->current_renderbuffer)
4008 FIXME("Not supported with fixed up depth stencil.\n");
4009 return;
4012 if (!(surface->Flags & SFLAG_LOCATIONS))
4014 FIXME("No up to date depth stencil location.\n");
4015 surface->Flags |= location;
4016 return;
4019 if (location == SFLAG_DS_OFFSCREEN)
4021 GLint old_binding = 0;
4022 GLenum bind_target;
4024 TRACE("Copying onscreen depth buffer to depth texture.\n");
4026 ENTER_GL();
4028 if (!device->depth_blt_texture)
4030 glGenTextures(1, &device->depth_blt_texture);
4033 /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
4034 * directly on the FBO texture. That's because we need to flip. */
4035 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4036 if (surface->texture_target == GL_TEXTURE_RECTANGLE_ARB)
4038 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
4039 bind_target = GL_TEXTURE_RECTANGLE_ARB;
4041 else
4043 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
4044 bind_target = GL_TEXTURE_2D;
4046 glBindTexture(bind_target, device->depth_blt_texture);
4047 glCopyTexImage2D(bind_target, surface->texture_level, surface->resource.format_desc->glInternal,
4048 0, 0, surface->currentDesc.Width, surface->currentDesc.Height, 0);
4049 glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4050 glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4051 glTexParameteri(bind_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
4052 glTexParameteri(bind_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
4053 glTexParameteri(bind_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
4054 glTexParameteri(bind_target, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
4055 glBindTexture(bind_target, old_binding);
4057 /* Setup the destination */
4058 if (!device->depth_blt_rb)
4060 gl_info->fbo_ops.glGenRenderbuffers(1, &device->depth_blt_rb);
4061 checkGLcall("glGenRenderbuffersEXT");
4063 if (device->depth_blt_rb_w != surface->currentDesc.Width
4064 || device->depth_blt_rb_h != surface->currentDesc.Height)
4066 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, device->depth_blt_rb);
4067 checkGLcall("glBindRenderbufferEXT");
4068 gl_info->fbo_ops.glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8,
4069 surface->currentDesc.Width, surface->currentDesc.Height);
4070 checkGLcall("glRenderbufferStorageEXT");
4071 device->depth_blt_rb_w = surface->currentDesc.Width;
4072 device->depth_blt_rb_h = surface->currentDesc.Height;
4075 context_bind_fbo(context, GL_FRAMEBUFFER, &context->dst_fbo);
4076 gl_info->fbo_ops.glFramebufferRenderbuffer(GL_FRAMEBUFFER,
4077 GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, device->depth_blt_rb);
4078 checkGLcall("glFramebufferRenderbufferEXT");
4079 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, surface, FALSE);
4081 /* Do the actual blit */
4082 surface_depth_blt(surface, gl_info, device->depth_blt_texture,
4083 surface->currentDesc.Width, surface->currentDesc.Height, bind_target);
4084 checkGLcall("depth_blt");
4086 if (context->current_fbo) context_bind_fbo(context, GL_FRAMEBUFFER, &context->current_fbo->id);
4087 else context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4089 LEAVE_GL();
4091 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
4093 else if (location == SFLAG_DS_ONSCREEN)
4095 TRACE("Copying depth texture to onscreen depth buffer.\n");
4097 ENTER_GL();
4099 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4100 surface_depth_blt(surface, gl_info, surface->texture_name,
4101 surface->currentDesc.Width, surface->currentDesc.Height, surface->texture_target);
4102 checkGLcall("depth_blt");
4104 if (context->current_fbo) context_bind_fbo(context, GL_FRAMEBUFFER, &context->current_fbo->id);
4106 LEAVE_GL();
4108 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
4110 else
4112 ERR("Invalid location (%#x) specified.\n", location);
4115 surface->Flags |= location;
4116 surface->ds_current_size.cx = surface->currentDesc.Width;
4117 surface->ds_current_size.cy = surface->currentDesc.Height;
4120 static void WINAPI IWineD3DSurfaceImpl_ModifyLocation(IWineD3DSurface *iface, DWORD flag, BOOL persistent) {
4121 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4122 IWineD3DBaseTexture *texture;
4123 IWineD3DSurfaceImpl *overlay;
4125 TRACE("(%p)->(%s, %s)\n", iface, debug_surflocation(flag),
4126 persistent ? "TRUE" : "FALSE");
4128 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
4130 if (surface_is_offscreen(This))
4132 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4133 if (flag & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE)) flag |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4135 else
4137 TRACE("Surface %p is an onscreen surface\n", iface);
4141 if(persistent) {
4142 if(((This->Flags & SFLAG_INTEXTURE) && !(flag & SFLAG_INTEXTURE)) ||
4143 ((This->Flags & SFLAG_INSRGBTEX) && !(flag & SFLAG_INSRGBTEX))) {
4144 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
4145 TRACE("Passing to container\n");
4146 IWineD3DBaseTexture_SetDirty(texture, TRUE);
4147 IWineD3DBaseTexture_Release(texture);
4150 This->Flags &= ~SFLAG_LOCATIONS;
4151 This->Flags |= flag;
4153 /* Redraw emulated overlays, if any */
4154 if(flag & SFLAG_INDRAWABLE && !list_empty(&This->overlays)) {
4155 LIST_FOR_EACH_ENTRY(overlay, &This->overlays, IWineD3DSurfaceImpl, overlay_entry) {
4156 IWineD3DSurface_DrawOverlay((IWineD3DSurface *) overlay);
4159 } else {
4160 if((This->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) && (flag & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX))) {
4161 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
4162 TRACE("Passing to container\n");
4163 IWineD3DBaseTexture_SetDirty(texture, TRUE);
4164 IWineD3DBaseTexture_Release(texture);
4167 This->Flags &= ~flag;
4170 if(!(This->Flags & SFLAG_LOCATIONS)) {
4171 ERR("%p: Surface does not have any up to date location\n", This);
4175 static inline void surface_blt_to_drawable(IWineD3DSurfaceImpl *This, const RECT *rect_in)
4177 IWineD3DDeviceImpl *device = This->resource.device;
4178 IWineD3DSwapChainImpl *swapchain;
4179 struct wined3d_context *context;
4180 RECT src_rect, dst_rect;
4182 surface_get_rect(This, rect_in, &src_rect);
4184 context = context_acquire(device, This);
4185 context_apply_blit_state(context, device);
4186 if (context->render_offscreen)
4188 dst_rect.left = src_rect.left;
4189 dst_rect.right = src_rect.right;
4190 dst_rect.top = src_rect.bottom;
4191 dst_rect.bottom = src_rect.top;
4193 else
4195 dst_rect = src_rect;
4198 if ((This->Flags & SFLAG_SWAPCHAIN) && This == ((IWineD3DSwapChainImpl *)This->container)->front_buffer)
4199 surface_translate_frontbuffer_coords(This, context->win_handle, &dst_rect);
4201 device->blitter->set_shader((IWineD3DDevice *) device, This);
4203 ENTER_GL();
4204 draw_textured_quad(This, &src_rect, &dst_rect, WINED3DTEXF_POINT);
4205 LEAVE_GL();
4207 device->blitter->unset_shader((IWineD3DDevice *) device);
4209 swapchain = (This->Flags & SFLAG_SWAPCHAIN) ? (IWineD3DSwapChainImpl *)This->container : NULL;
4210 if (wined3d_settings.strict_draw_ordering || (swapchain
4211 && (This == swapchain->front_buffer || swapchain->num_contexts > 1)))
4212 wglFlush(); /* Flush to ensure ordering across contexts. */
4214 context_release(context);
4217 /*****************************************************************************
4218 * IWineD3DSurface::LoadLocation
4220 * Copies the current surface data from wherever it is to the requested
4221 * location. The location is one of the surface flags, SFLAG_INSYSMEM,
4222 * SFLAG_INTEXTURE and SFLAG_INDRAWABLE. When the surface is current in
4223 * multiple locations, the gl texture is preferred over the drawable, which is
4224 * preferred over system memory. The PBO counts as system memory. If rect is
4225 * not NULL, only the specified rectangle is copied (only supported for
4226 * sysmem<->drawable copies at the moment). If rect is NULL, the destination
4227 * location is marked up to date after the copy.
4229 * Parameters:
4230 * flag: Surface location flag to be updated
4231 * rect: rectangle to be copied
4233 * Returns:
4234 * WINED3D_OK on success
4235 * WINED3DERR_DEVICELOST on an internal error
4237 *****************************************************************************/
4238 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadLocation(IWineD3DSurface *iface, DWORD flag, const RECT *rect) {
4239 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4240 IWineD3DDeviceImpl *device = This->resource.device;
4241 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4242 struct wined3d_format_desc desc;
4243 CONVERT_TYPES convert;
4244 int width, pitch, outpitch;
4245 BYTE *mem;
4246 BOOL drawable_read_ok = TRUE;
4247 BOOL in_fbo = FALSE;
4249 if (This->resource.usage & WINED3DUSAGE_DEPTHSTENCIL)
4251 if (flag == SFLAG_INTEXTURE)
4253 struct wined3d_context *context = context_acquire(device, NULL);
4254 surface_load_ds_location(This, context, SFLAG_DS_OFFSCREEN);
4255 context_release(context);
4256 return WINED3D_OK;
4258 else
4260 FIXME("Unimplemented location %#x for depth/stencil buffers.\n", flag);
4261 return WINED3DERR_INVALIDCALL;
4265 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
4267 if (surface_is_offscreen(This))
4269 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets.
4270 * Prefer SFLAG_INTEXTURE. */
4271 if (flag == SFLAG_INDRAWABLE) flag = SFLAG_INTEXTURE;
4272 drawable_read_ok = FALSE;
4273 in_fbo = TRUE;
4275 else
4277 TRACE("Surface %p is an onscreen surface\n", iface);
4281 TRACE("(%p)->(%s, %p)\n", iface, debug_surflocation(flag), rect);
4282 if(rect) {
4283 TRACE("Rectangle: (%d,%d)-(%d,%d)\n", rect->left, rect->top, rect->right, rect->bottom);
4286 if(This->Flags & flag) {
4287 TRACE("Location already up to date\n");
4288 return WINED3D_OK;
4291 if(!(This->Flags & SFLAG_LOCATIONS)) {
4292 ERR("%p: Surface does not have any up to date location\n", This);
4293 This->Flags |= SFLAG_LOST;
4294 return WINED3DERR_DEVICELOST;
4297 if(flag == SFLAG_INSYSMEM) {
4298 surface_prepare_system_memory(This);
4300 /* Download the surface to system memory */
4301 if (This->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX))
4303 struct wined3d_context *context = NULL;
4305 if (!device->isInDraw) context = context_acquire(device, NULL);
4307 surface_bind_and_dirtify(This, !(This->Flags & SFLAG_INTEXTURE));
4308 surface_download_data(This, gl_info);
4310 if (context) context_release(context);
4312 else
4314 /* Note: It might be faster to download into a texture first. */
4315 read_from_framebuffer(This, rect,
4316 This->resource.allocatedMemory,
4317 IWineD3DSurface_GetPitch(iface));
4319 } else if(flag == SFLAG_INDRAWABLE) {
4320 if(This->Flags & SFLAG_INTEXTURE) {
4321 surface_blt_to_drawable(This, rect);
4322 } else {
4323 int byte_count;
4324 if((This->Flags & SFLAG_LOCATIONS) == SFLAG_INSRGBTEX) {
4325 /* This needs a shader to convert the srgb data sampled from the GL texture into RGB
4326 * values, otherwise we get incorrect values in the target. For now go the slow way
4327 * via a system memory copy
4329 IWineD3DSurfaceImpl_LoadLocation(iface, SFLAG_INSYSMEM, rect);
4332 d3dfmt_get_conv(This, FALSE /* We need color keying */, FALSE /* We won't use textures */, &desc, &convert);
4334 /* The width is in 'length' not in bytes */
4335 width = This->currentDesc.Width;
4336 pitch = IWineD3DSurface_GetPitch(iface);
4338 /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4339 * but it isn't set (yet) in all cases it is getting called. */
4340 if ((convert != NO_CONVERSION) && (This->Flags & SFLAG_PBO))
4342 struct wined3d_context *context = NULL;
4344 TRACE("Removing the pbo attached to surface %p\n", This);
4346 if (!device->isInDraw) context = context_acquire(device, NULL);
4347 surface_remove_pbo(This, gl_info);
4348 if (context) context_release(context);
4351 if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
4352 int height = This->currentDesc.Height;
4353 byte_count = desc.conv_byte_count;
4355 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4356 outpitch = width * byte_count;
4357 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4359 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4360 if(!mem) {
4361 ERR("Out of memory %d, %d!\n", outpitch, height);
4362 return WINED3DERR_OUTOFVIDEOMEMORY;
4364 d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
4366 This->Flags |= SFLAG_CONVERTED;
4367 } else {
4368 This->Flags &= ~SFLAG_CONVERTED;
4369 mem = This->resource.allocatedMemory;
4370 byte_count = desc.byte_count;
4373 flush_to_framebuffer_drawpixels(This, desc.glFormat, desc.glType, byte_count, mem);
4375 /* Don't delete PBO memory */
4376 if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
4377 HeapFree(GetProcessHeap(), 0, mem);
4379 } else /* if(flag & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) */ {
4380 if (drawable_read_ok && (This->Flags & SFLAG_INDRAWABLE)) {
4381 read_from_framebuffer_texture(This, flag == SFLAG_INSRGBTEX);
4383 else
4385 /* Upload from system memory */
4386 BOOL srgb = flag == SFLAG_INSRGBTEX;
4387 struct wined3d_context *context = NULL;
4389 d3dfmt_get_conv(This, TRUE /* We need color keying */, TRUE /* We will use textures */,
4390 &desc, &convert);
4392 if(srgb) {
4393 if((This->Flags & (SFLAG_INTEXTURE | SFLAG_INSYSMEM)) == SFLAG_INTEXTURE) {
4394 /* Performance warning ... */
4395 FIXME("%p: Downloading rgb texture to reload it as srgb\n", This);
4396 IWineD3DSurfaceImpl_LoadLocation(iface, SFLAG_INSYSMEM, rect);
4398 } else {
4399 if((This->Flags & (SFLAG_INSRGBTEX | SFLAG_INSYSMEM)) == SFLAG_INSRGBTEX) {
4400 /* Performance warning ... */
4401 FIXME("%p: Downloading srgb texture to reload it as rgb\n", This);
4402 IWineD3DSurfaceImpl_LoadLocation(iface, SFLAG_INSYSMEM, rect);
4405 if(!(This->Flags & SFLAG_INSYSMEM)) {
4406 /* Should not happen */
4407 ERR("Trying to load a texture from sysmem, but SFLAG_INSYSMEM is not set\n");
4408 /* Lets hope we get it from somewhere... */
4409 IWineD3DSurfaceImpl_LoadLocation(iface, SFLAG_INSYSMEM, rect);
4412 if (!device->isInDraw) context = context_acquire(device, NULL);
4414 surface_prepare_texture(This, gl_info, srgb);
4415 surface_bind_and_dirtify(This, srgb);
4417 if(This->CKeyFlags & WINEDDSD_CKSRCBLT) {
4418 This->Flags |= SFLAG_GLCKEY;
4419 This->glCKey = This->SrcBltCKey;
4421 else This->Flags &= ~SFLAG_GLCKEY;
4423 /* The width is in 'length' not in bytes */
4424 width = This->currentDesc.Width;
4425 pitch = IWineD3DSurface_GetPitch(iface);
4427 /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4428 * but it isn't set (yet) in all cases it is getting called. */
4429 if(((convert != NO_CONVERSION) || desc.convert) && (This->Flags & SFLAG_PBO)) {
4430 TRACE("Removing the pbo attached to surface %p\n", This);
4431 surface_remove_pbo(This, gl_info);
4434 if(desc.convert) {
4435 /* This code is entered for texture formats which need a fixup. */
4436 int height = This->currentDesc.Height;
4438 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4439 outpitch = width * desc.conv_byte_count;
4440 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4442 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4443 if(!mem) {
4444 ERR("Out of memory %d, %d!\n", outpitch, height);
4445 if (context) context_release(context);
4446 return WINED3DERR_OUTOFVIDEOMEMORY;
4448 desc.convert(This->resource.allocatedMemory, mem, pitch, width, height);
4449 } else if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
4450 /* This code is only entered for color keying fixups */
4451 int height = This->currentDesc.Height;
4453 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4454 outpitch = width * desc.conv_byte_count;
4455 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4457 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4458 if(!mem) {
4459 ERR("Out of memory %d, %d!\n", outpitch, height);
4460 if (context) context_release(context);
4461 return WINED3DERR_OUTOFVIDEOMEMORY;
4463 d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
4464 } else {
4465 mem = This->resource.allocatedMemory;
4468 /* Make sure the correct pitch is used */
4469 ENTER_GL();
4470 glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
4471 LEAVE_GL();
4473 if (mem || (This->Flags & SFLAG_PBO))
4474 surface_upload_data(This, gl_info, &desc, srgb, mem);
4476 /* Restore the default pitch */
4477 ENTER_GL();
4478 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
4479 LEAVE_GL();
4481 if (context) context_release(context);
4483 /* Don't delete PBO memory */
4484 if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
4485 HeapFree(GetProcessHeap(), 0, mem);
4489 if(rect == NULL) {
4490 This->Flags |= flag;
4493 if (in_fbo && (This->Flags & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE))) {
4494 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4495 This->Flags |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4498 return WINED3D_OK;
4501 static HRESULT WINAPI IWineD3DSurfaceImpl_SetContainer(IWineD3DSurface *iface, IWineD3DBase *container)
4503 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4504 IWineD3DSwapChain *swapchain = NULL;
4506 /* Update the drawable size method */
4507 if(container) {
4508 IWineD3DBase_QueryInterface(container, &IID_IWineD3DSwapChain, (void **) &swapchain);
4510 if(swapchain) {
4511 This->get_drawable_size = get_drawable_size_swapchain;
4512 IWineD3DSwapChain_Release(swapchain);
4513 } else if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
4514 switch(wined3d_settings.offscreen_rendering_mode) {
4515 case ORM_FBO: This->get_drawable_size = get_drawable_size_fbo; break;
4516 case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
4520 return IWineD3DBaseSurfaceImpl_SetContainer(iface, container);
4523 static WINED3DSURFTYPE WINAPI IWineD3DSurfaceImpl_GetImplType(IWineD3DSurface *iface) {
4524 return SURFACE_OPENGL;
4527 static HRESULT WINAPI IWineD3DSurfaceImpl_DrawOverlay(IWineD3DSurface *iface) {
4528 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4529 HRESULT hr;
4531 /* If there's no destination surface there is nothing to do */
4532 if(!This->overlay_dest) return WINED3D_OK;
4534 /* Blt calls ModifyLocation on the dest surface, which in turn calls DrawOverlay to
4535 * update the overlay. Prevent an endless recursion
4537 if(This->overlay_dest->Flags & SFLAG_INOVERLAYDRAW) {
4538 return WINED3D_OK;
4540 This->overlay_dest->Flags |= SFLAG_INOVERLAYDRAW;
4541 hr = IWineD3DSurfaceImpl_Blt((IWineD3DSurface *) This->overlay_dest, &This->overlay_destrect,
4542 iface, &This->overlay_srcrect, WINEDDBLT_WAIT,
4543 NULL, WINED3DTEXF_LINEAR);
4544 This->overlay_dest->Flags &= ~SFLAG_INOVERLAYDRAW;
4546 return hr;
4549 BOOL surface_is_offscreen(IWineD3DSurfaceImpl *surface)
4551 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)surface->container;
4553 /* Not on a swapchain - must be offscreen */
4554 if (!(surface->Flags & SFLAG_SWAPCHAIN)) return TRUE;
4556 /* The front buffer is always onscreen */
4557 if (surface == swapchain->front_buffer) return FALSE;
4559 /* If the swapchain is rendered to an FBO, the backbuffer is
4560 * offscreen, otherwise onscreen */
4561 return swapchain->render_to_fbo;
4564 const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl =
4566 /* IUnknown */
4567 IWineD3DBaseSurfaceImpl_QueryInterface,
4568 IWineD3DBaseSurfaceImpl_AddRef,
4569 IWineD3DSurfaceImpl_Release,
4570 /* IWineD3DResource */
4571 IWineD3DBaseSurfaceImpl_GetParent,
4572 IWineD3DBaseSurfaceImpl_SetPrivateData,
4573 IWineD3DBaseSurfaceImpl_GetPrivateData,
4574 IWineD3DBaseSurfaceImpl_FreePrivateData,
4575 IWineD3DBaseSurfaceImpl_SetPriority,
4576 IWineD3DBaseSurfaceImpl_GetPriority,
4577 IWineD3DSurfaceImpl_PreLoad,
4578 IWineD3DSurfaceImpl_UnLoad,
4579 IWineD3DBaseSurfaceImpl_GetType,
4580 /* IWineD3DSurface */
4581 IWineD3DBaseSurfaceImpl_GetContainer,
4582 IWineD3DBaseSurfaceImpl_GetDesc,
4583 IWineD3DSurfaceImpl_LockRect,
4584 IWineD3DSurfaceImpl_UnlockRect,
4585 IWineD3DSurfaceImpl_GetDC,
4586 IWineD3DSurfaceImpl_ReleaseDC,
4587 IWineD3DSurfaceImpl_Flip,
4588 IWineD3DSurfaceImpl_Blt,
4589 IWineD3DBaseSurfaceImpl_GetBltStatus,
4590 IWineD3DBaseSurfaceImpl_GetFlipStatus,
4591 IWineD3DBaseSurfaceImpl_IsLost,
4592 IWineD3DBaseSurfaceImpl_Restore,
4593 IWineD3DSurfaceImpl_BltFast,
4594 IWineD3DBaseSurfaceImpl_GetPalette,
4595 IWineD3DBaseSurfaceImpl_SetPalette,
4596 IWineD3DSurfaceImpl_RealizePalette,
4597 IWineD3DBaseSurfaceImpl_SetColorKey,
4598 IWineD3DBaseSurfaceImpl_GetPitch,
4599 IWineD3DSurfaceImpl_SetMem,
4600 IWineD3DBaseSurfaceImpl_SetOverlayPosition,
4601 IWineD3DBaseSurfaceImpl_GetOverlayPosition,
4602 IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder,
4603 IWineD3DBaseSurfaceImpl_UpdateOverlay,
4604 IWineD3DBaseSurfaceImpl_SetClipper,
4605 IWineD3DBaseSurfaceImpl_GetClipper,
4606 /* Internal use: */
4607 IWineD3DSurfaceImpl_LoadTexture,
4608 IWineD3DSurfaceImpl_BindTexture,
4609 IWineD3DSurfaceImpl_SetContainer,
4610 IWineD3DBaseSurfaceImpl_GetData,
4611 IWineD3DSurfaceImpl_SetFormat,
4612 IWineD3DSurfaceImpl_PrivateSetup,
4613 IWineD3DSurfaceImpl_ModifyLocation,
4614 IWineD3DSurfaceImpl_LoadLocation,
4615 IWineD3DSurfaceImpl_GetImplType,
4616 IWineD3DSurfaceImpl_DrawOverlay
4619 static HRESULT ffp_blit_alloc(IWineD3DDevice *iface) { return WINED3D_OK; }
4620 /* Context activation is done by the caller. */
4621 static void ffp_blit_free(IWineD3DDevice *iface) { }
4623 /* This function is used in case of 8bit paletted textures using GL_EXT_paletted_texture */
4624 /* Context activation is done by the caller. */
4625 static void ffp_blit_p8_upload_palette(IWineD3DSurfaceImpl *surface, const struct wined3d_gl_info *gl_info)
4627 BYTE table[256][4];
4628 BOOL colorkey_active = (surface->CKeyFlags & WINEDDSD_CKSRCBLT) ? TRUE : FALSE;
4630 d3dfmt_p8_init_palette(surface, table, colorkey_active);
4632 TRACE("Using GL_EXT_PALETTED_TEXTURE for 8-bit paletted texture support\n");
4633 ENTER_GL();
4634 GL_EXTCALL(glColorTableEXT(surface->texture_target, GL_RGBA, 256, GL_RGBA, GL_UNSIGNED_BYTE, table));
4635 LEAVE_GL();
4638 /* Context activation is done by the caller. */
4639 static HRESULT ffp_blit_set(IWineD3DDevice *iface, IWineD3DSurfaceImpl *surface)
4641 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
4642 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4643 enum complex_fixup fixup = get_complex_fixup(surface->resource.format_desc->color_fixup);
4645 /* When EXT_PALETTED_TEXTURE is around, palette conversion is done by the GPU
4646 * else the surface is converted in software at upload time in LoadLocation.
4648 if(fixup == COMPLEX_FIXUP_P8 && gl_info->supported[EXT_PALETTED_TEXTURE])
4649 ffp_blit_p8_upload_palette(surface, gl_info);
4651 ENTER_GL();
4652 glEnable(surface->texture_target);
4653 checkGLcall("glEnable(surface->texture_target)");
4654 LEAVE_GL();
4655 return WINED3D_OK;
4658 /* Context activation is done by the caller. */
4659 static void ffp_blit_unset(IWineD3DDevice *iface)
4661 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
4662 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4664 ENTER_GL();
4665 glDisable(GL_TEXTURE_2D);
4666 checkGLcall("glDisable(GL_TEXTURE_2D)");
4667 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
4669 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
4670 checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
4672 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4674 glDisable(GL_TEXTURE_RECTANGLE_ARB);
4675 checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
4677 LEAVE_GL();
4680 static BOOL ffp_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4681 const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
4682 const struct wined3d_format_desc *src_format_desc,
4683 const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
4684 const struct wined3d_format_desc *dst_format_desc)
4686 enum complex_fixup src_fixup;
4688 if (blit_op == BLIT_OP_COLOR_FILL)
4690 if (!(dst_usage & WINED3DUSAGE_RENDERTARGET))
4692 TRACE("Color fill not supported\n");
4693 return FALSE;
4696 return TRUE;
4699 src_fixup = get_complex_fixup(src_format_desc->color_fixup);
4700 if (TRACE_ON(d3d_surface) && TRACE_ON(d3d))
4702 TRACE("Checking support for fixup:\n");
4703 dump_color_fixup_desc(src_format_desc->color_fixup);
4706 if (blit_op != BLIT_OP_BLIT)
4708 TRACE("Unsupported blit_op=%d\n", blit_op);
4709 return FALSE;
4712 if (!is_identity_fixup(dst_format_desc->color_fixup))
4714 TRACE("Destination fixups are not supported\n");
4715 return FALSE;
4718 if (src_fixup == COMPLEX_FIXUP_P8 && gl_info->supported[EXT_PALETTED_TEXTURE])
4720 TRACE("P8 fixup supported\n");
4721 return TRUE;
4724 /* We only support identity conversions. */
4725 if (is_identity_fixup(src_format_desc->color_fixup))
4727 TRACE("[OK]\n");
4728 return TRUE;
4731 TRACE("[FAILED]\n");
4732 return FALSE;
4735 static HRESULT ffp_blit_color_fill(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *dst_surface, const RECT *dst_rect, DWORD fill_color)
4737 return IWineD3DDeviceImpl_ClearSurface(device, dst_surface, 1 /* Number of rectangles */,
4738 (const WINED3DRECT*)dst_rect, WINED3DCLEAR_TARGET, fill_color, 0.0f /* Z */, 0 /* Stencil */);
4741 const struct blit_shader ffp_blit = {
4742 ffp_blit_alloc,
4743 ffp_blit_free,
4744 ffp_blit_set,
4745 ffp_blit_unset,
4746 ffp_blit_supported,
4747 ffp_blit_color_fill
4750 static HRESULT cpu_blit_alloc(IWineD3DDevice *iface)
4752 return WINED3D_OK;
4755 /* Context activation is done by the caller. */
4756 static void cpu_blit_free(IWineD3DDevice *iface)
4760 /* Context activation is done by the caller. */
4761 static HRESULT cpu_blit_set(IWineD3DDevice *iface, IWineD3DSurfaceImpl *surface)
4763 return WINED3D_OK;
4766 /* Context activation is done by the caller. */
4767 static void cpu_blit_unset(IWineD3DDevice *iface)
4771 static BOOL cpu_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4772 const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
4773 const struct wined3d_format_desc *src_format_desc,
4774 const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
4775 const struct wined3d_format_desc *dst_format_desc)
4777 if (blit_op == BLIT_OP_COLOR_FILL)
4779 return TRUE;
4782 return FALSE;
4785 static HRESULT cpu_blit_color_fill(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *dst_surface, const RECT *dst_rect, DWORD fill_color)
4787 WINEDDBLTFX BltFx;
4788 memset(&BltFx, 0, sizeof(BltFx));
4789 BltFx.dwSize = sizeof(BltFx);
4790 BltFx.u5.dwFillColor = color_convert_argb_to_fmt(fill_color, dst_surface->resource.format_desc->format);
4791 return IWineD3DBaseSurfaceImpl_Blt((IWineD3DSurface*)dst_surface, dst_rect, NULL, NULL, WINEDDBLT_COLORFILL, &BltFx, WINED3DTEXF_POINT);
4794 const struct blit_shader cpu_blit = {
4795 cpu_blit_alloc,
4796 cpu_blit_free,
4797 cpu_blit_set,
4798 cpu_blit_unset,
4799 cpu_blit_supported,
4800 cpu_blit_color_fill
4803 static BOOL fbo_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4804 const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
4805 const struct wined3d_format_desc *src_format_desc,
4806 const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
4807 const struct wined3d_format_desc *dst_format_desc)
4809 if ((wined3d_settings.offscreen_rendering_mode != ORM_FBO) || !gl_info->fbo_ops.glBlitFramebuffer)
4810 return FALSE;
4812 /* We only support blitting. Things like color keying / color fill should
4813 * be handled by other blitters.
4815 if (blit_op != BLIT_OP_BLIT)
4816 return FALSE;
4818 /* Source and/or destination need to be on the GL side */
4819 if (src_pool == WINED3DPOOL_SYSTEMMEM || dst_pool == WINED3DPOOL_SYSTEMMEM)
4820 return FALSE;
4822 if(!((src_format_desc->Flags & WINED3DFMT_FLAG_FBO_ATTACHABLE) || (src_usage & WINED3DUSAGE_RENDERTARGET))
4823 && ((dst_format_desc->Flags & WINED3DFMT_FLAG_FBO_ATTACHABLE) || (dst_usage & WINED3DUSAGE_RENDERTARGET)))
4824 return FALSE;
4826 if (!is_identity_fixup(src_format_desc->color_fixup) ||
4827 !is_identity_fixup(dst_format_desc->color_fixup))
4828 return FALSE;
4830 if (!(src_format_desc->format == dst_format_desc->format
4831 || (is_identity_fixup(src_format_desc->color_fixup)
4832 && is_identity_fixup(dst_format_desc->color_fixup))))
4833 return FALSE;
4835 return TRUE;