wined3d: Add a method for surface location updates.
[wine/wine64.git] / dlls / wined3d / surface.c
blobb825683577dab09f527b6bdd5dd2f73b0f7b4fdf
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 Stefan Dösinger for CodeWeavers
11 * Copyright 2007 Henri Verbeet
12 * Copyright 2006-2007 Roderick Colenbrander
14 * This library is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Lesser General Public
16 * License as published by the Free Software Foundation; either
17 * version 2.1 of the License, or (at your option) any later version.
19 * This library is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * Lesser General Public License for more details.
24 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, write to the Free Software
26 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
29 #include "config.h"
30 #include "wine/port.h"
31 #include "wined3d_private.h"
33 WINE_DEFAULT_DEBUG_CHANNEL(d3d_surface);
34 #define GLINFO_LOCATION This->resource.wineD3DDevice->adapter->gl_info
36 HRESULT d3dfmt_convert_surface(BYTE *src, BYTE *dst, UINT pitch, UINT width, UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *surf);
37 static void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey);
39 static void surface_download_data(IWineD3DSurfaceImpl *This) {
40 if (!(This->resource.allocatedMemory || This->Flags & SFLAG_PBO)) This->resource.allocatedMemory = HeapAlloc(GetProcessHeap(), 0, This->resource.size + 4);
41 if (This->resource.format == WINED3DFMT_DXT1 ||
42 This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
43 This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) {
44 if (!GL_SUPPORT(EXT_TEXTURE_COMPRESSION_S3TC)) { /* We can assume this as the texture would not have been created otherwise */
45 FIXME("(%p) : Attempting to lock a compressed texture when texture compression isn't supported by opengl\n", This);
46 } else {
47 TRACE("(%p) : Calling glGetCompressedTexImageARB level %d, format %#x, type %#x, data %p\n", This, This->glDescription.level,
48 This->glDescription.glFormat, This->glDescription.glType, This->resource.allocatedMemory);
50 GL_EXTCALL(glGetCompressedTexImageARB(This->glDescription.target, This->glDescription.level, This->resource.allocatedMemory));
51 checkGLcall("glGetCompressedTexImageARB()");
53 } else {
54 void *mem;
55 int src_pitch = 0;
56 int dst_pitch = 0;
58 if(This->Flags & SFLAG_CONVERTED) {
59 FIXME("Read back converted textures unsupported\n");
60 return;
63 if (This->Flags & SFLAG_NONPOW2) {
64 unsigned char alignment = This->resource.wineD3DDevice->surface_alignment;
65 src_pitch = This->bytesPerPixel * This->pow2Width;
66 dst_pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);
67 src_pitch = (src_pitch + alignment - 1) & ~(alignment - 1);
68 mem = HeapAlloc(GetProcessHeap(), 0, src_pitch * This->pow2Height);
69 } else {
70 mem = This->resource.allocatedMemory;
73 TRACE("(%p) : Calling glGetTexImage level %d, format %#x, type %#x, data %p\n", This, This->glDescription.level,
74 This->glDescription.glFormat, This->glDescription.glType, mem);
76 if(This->Flags & SFLAG_PBO) {
77 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
78 checkGLcall("glBindBufferARB");
80 glGetTexImage(This->glDescription.target, This->glDescription.level, This->glDescription.glFormat,
81 This->glDescription.glType, NULL);
82 checkGLcall("glGetTexImage()");
84 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
85 checkGLcall("glBindBufferARB");
86 } else {
87 glGetTexImage(This->glDescription.target, This->glDescription.level, This->glDescription.glFormat,
88 This->glDescription.glType, mem);
89 checkGLcall("glGetTexImage()");
92 if (This->Flags & SFLAG_NONPOW2) {
93 LPBYTE src_data, dst_data;
94 int y;
96 * Some games (e.g. warhammer 40k) don't work properly with the odd pitches, preventing
97 * the surface pitch from being used to box non-power2 textures. Instead we have to use a hack to
98 * repack the texture so that the bpp * width pitch can be used instead of bpp * pow2width.
100 * We're doing this...
102 * instead of boxing the texture :
103 * |<-texture width ->| -->pow2width| /\
104 * |111111111111111111| | |
105 * |222 Texture 222222| boxed empty | texture height
106 * |3333 Data 33333333| | |
107 * |444444444444444444| | \/
108 * ----------------------------------- |
109 * | boxed empty | boxed empty | pow2height
110 * | | | \/
111 * -----------------------------------
114 * we're repacking the data to the expected texture width
116 * |<-texture width ->| -->pow2width| /\
117 * |111111111111111111222222222222222| |
118 * |222333333333333333333444444444444| texture height
119 * |444444 | |
120 * | | \/
121 * | | |
122 * | empty | pow2height
123 * | | \/
124 * -----------------------------------
126 * == is the same as
128 * |<-texture width ->| /\
129 * |111111111111111111|
130 * |222222222222222222|texture height
131 * |333333333333333333|
132 * |444444444444444444| \/
133 * --------------------
135 * this also means that any references to allocatedMemory should work with the data as if were a
136 * standard texture with a non-power2 width instead of texture boxed up to be a power2 texture.
138 * internally the texture is still stored in a boxed format so any references to textureName will
139 * get a boxed texture with width pow2width and not a texture of width currentDesc.Width.
141 * Performance should not be an issue, because applications normally do not lock the surfaces when
142 * rendering. If an app does, the SFLAG_DYNLOCK flag will kick in and the memory copy won't be released,
143 * and doesn't have to be re-read.
145 src_data = mem;
146 dst_data = This->resource.allocatedMemory;
147 TRACE("(%p) : Repacking the surface data from pitch %d to pitch %d\n", This, src_pitch, dst_pitch);
148 for (y = 1 ; y < This->currentDesc.Height; y++) {
149 /* skip the first row */
150 src_data += src_pitch;
151 dst_data += dst_pitch;
152 memcpy(dst_data, src_data, dst_pitch);
155 HeapFree(GetProcessHeap(), 0, mem);
158 /* Surface has now been downloaded */
159 This->Flags |= SFLAG_INSYSMEM;
162 static void surface_upload_data(IWineD3DSurfaceImpl *This, GLenum internal, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *data) {
163 if (This->resource.format == WINED3DFMT_DXT1 ||
164 This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
165 This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) {
166 if (!GL_SUPPORT(EXT_TEXTURE_COMPRESSION_S3TC)) {
167 FIXME("Using DXT1/3/5 without advertized support\n");
168 } else {
169 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
170 /* Neither NONPOW2, DIBSECTION nor OVERSIZE flags can be set on compressed textures */
171 This->Flags |= SFLAG_CLIENT;
174 /* glCompressedTexSubImage2D for uploading and glTexImage2D for allocating does not work well on some drivers(r200 dri, MacOS ATI driver)
175 * glCompressedTexImage2D does not accept NULL pointers. So for compressed textures surface_allocate_surface does nothing, and this
176 * function uses glCompressedTexImage2D instead of the SubImage call
178 TRACE("(%p) : Calling glCompressedTexSubImage2D w %d, h %d, data %p\n", This, width, height, data);
179 ENTER_GL();
181 if(This->Flags & SFLAG_PBO) {
182 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
183 checkGLcall("glBindBufferARB");
184 TRACE("(%p) pbo: %#x, data: %p\n", This, This->pbo, data);
186 GL_EXTCALL(glCompressedTexImage2DARB(This->glDescription.target, This->glDescription.level, internal,
187 width, height, 0 /* border */, This->resource.size, NULL));
188 checkGLcall("glCompressedTexSubImage2D");
190 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
191 checkGLcall("glBindBufferARB");
192 } else {
193 GL_EXTCALL(glCompressedTexImage2DARB(This->glDescription.target, This->glDescription.level, internal,
194 width, height, 0 /* border */, This->resource.size, data));
195 checkGLcall("glCompressedTexSubImage2D");
197 LEAVE_GL();
199 } else {
200 TRACE("(%p) : Calling glTexSubImage2D w %d, h %d, data, %p\n", This, width, height, data);
201 ENTER_GL();
203 if(This->Flags & SFLAG_PBO) {
204 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
205 checkGLcall("glBindBufferARB");
206 TRACE("(%p) pbo: %#x, data: %p\n", This, This->pbo, data);
208 glTexSubImage2D(This->glDescription.target, This->glDescription.level, 0, 0, width, height, format, type, NULL);
209 checkGLcall("glTexSubImage2D");
211 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
212 checkGLcall("glBindBufferARB");
214 else {
215 glTexSubImage2D(This->glDescription.target, This->glDescription.level, 0, 0, width, height, format, type, data);
216 checkGLcall("glTexSubImage2D");
219 LEAVE_GL();
223 static void surface_allocate_surface(IWineD3DSurfaceImpl *This, GLenum internal, GLsizei width, GLsizei height, GLenum format, GLenum type) {
224 BOOL enable_client_storage = FALSE;
226 TRACE("(%p) : Creating surface (target %#x) level %d, d3d format %s, internal format %#x, width %d, height %d, gl format %#x, gl type=%#x\n", This,
227 This->glDescription.target, This->glDescription.level, debug_d3dformat(This->resource.format), internal, width, height, format, type);
229 if (This->resource.format == WINED3DFMT_DXT1 ||
230 This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
231 This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) {
232 /* glCompressedTexImage2D does not accept NULL pointers, so we cannot allocate a compressed texture without uploading data */
233 TRACE("Not allocating compressed surfaces, surface_upload_data will specify them\n");
234 return;
237 ENTER_GL();
239 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
240 if(This->Flags & (SFLAG_NONPOW2 | SFLAG_DIBSECTION | SFLAG_OVERSIZE | SFLAG_CONVERTED) || This->resource.allocatedMemory == NULL) {
241 /* In some cases we want to disable client storage.
242 * SFLAG_NONPOW2 has a bigger opengl texture than the client memory, and different pitches
243 * SFLAG_DIBSECTION: Dibsections may have read / write protections on the memory. Avoid issues...
244 * SFLAG_OVERSIZE: The gl texture is smaller than the allocated memory
245 * SFLAG_CONVERTED: The conversion destination memory is freed after loading the surface
246 * allocatedMemory == NULL: Not defined in the extension. Seems to disable client storage effectively
248 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
249 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
250 This->Flags &= ~SFLAG_CLIENT;
251 enable_client_storage = TRUE;
252 } else {
253 This->Flags |= SFLAG_CLIENT;
254 /* Below point opengl to our allocated texture memory */
257 glTexImage2D(This->glDescription.target, This->glDescription.level, internal, width, height, 0, format, type,
258 This->Flags & SFLAG_CLIENT ? This->resource.allocatedMemory : NULL);
259 checkGLcall("glTexImage2D");
261 if(enable_client_storage) {
262 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
263 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
265 LEAVE_GL();
267 This->Flags |= SFLAG_ALLOCATED;
270 /* In D3D the depth stencil dimensions have to be greater than or equal to the
271 * render target dimensions. With FBOs, the dimensions have to be an exact match. */
272 /* TODO: We should synchronize the renderbuffer's content with the texture's content. */
273 void surface_set_compatible_renderbuffer(IWineD3DSurface *iface, unsigned int width, unsigned int height) {
274 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
275 renderbuffer_entry_t *entry;
276 GLuint renderbuffer = 0;
277 unsigned int src_width, src_height;
279 src_width = This->pow2Width;
280 src_height = This->pow2Height;
282 /* A depth stencil smaller than the render target is not valid */
283 if (width > src_width || height > src_height) return;
285 /* Remove any renderbuffer set if the sizes match */
286 if (width == src_width && height == src_height) {
287 This->current_renderbuffer = NULL;
288 return;
291 /* Look if we've already got a renderbuffer of the correct dimensions */
292 LIST_FOR_EACH_ENTRY(entry, &This->renderbuffers, renderbuffer_entry_t, entry) {
293 if (entry->width == width && entry->height == height) {
294 renderbuffer = entry->id;
295 This->current_renderbuffer = entry;
296 break;
300 if (!renderbuffer) {
301 const GlPixelFormatDesc *glDesc;
302 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
304 GL_EXTCALL(glGenRenderbuffersEXT(1, &renderbuffer));
305 GL_EXTCALL(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, renderbuffer));
306 GL_EXTCALL(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, glDesc->glFormat, width, height));
308 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(renderbuffer_entry_t));
309 entry->width = width;
310 entry->height = height;
311 entry->id = renderbuffer;
312 list_add_head(&This->renderbuffers, &entry->entry);
314 This->current_renderbuffer = entry;
317 checkGLcall("set_compatible_renderbuffer");
320 GLenum surface_get_gl_buffer(IWineD3DSurface *iface, IWineD3DSwapChain *swapchain) {
321 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
322 IWineD3DSwapChainImpl *swapchain_impl = (IWineD3DSwapChainImpl *)swapchain;
324 TRACE("(%p) : swapchain %p\n", This, swapchain);
326 if (swapchain_impl->backBuffer && swapchain_impl->backBuffer[0] == iface) {
327 TRACE("Returning GL_BACK\n");
328 return GL_BACK;
329 } else if (swapchain_impl->frontBuffer == iface) {
330 TRACE("Returning GL_FRONT\n");
331 return GL_FRONT;
334 FIXME("Higher back buffer, returning GL_BACK\n");
335 return GL_BACK;
338 ULONG WINAPI IWineD3DSurfaceImpl_Release(IWineD3DSurface *iface) {
339 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
340 ULONG ref = InterlockedDecrement(&This->resource.ref);
341 TRACE("(%p) : Releasing from %d\n", This, ref + 1);
342 if (ref == 0) {
343 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->resource.wineD3DDevice;
344 renderbuffer_entry_t *entry, *entry2;
345 TRACE("(%p) : cleaning up\n", This);
347 if (This->glDescription.textureName != 0) { /* release the openGL texture.. */
349 /* Need a context to destroy the texture. Use the currently active render target, but only if
350 * the primary render target exists. Otherwise lastActiveRenderTarget is garbage, see above.
351 * When destroying the primary rt, Uninit3D will activate a context before doing anything
353 if(device->render_targets && device->render_targets[0]) {
354 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
357 TRACE("Deleting texture %d\n", This->glDescription.textureName);
358 ENTER_GL();
359 glDeleteTextures(1, &This->glDescription.textureName);
360 LEAVE_GL();
363 if(This->Flags & SFLAG_PBO) {
364 /* Delete the PBO */
365 GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
368 if(This->Flags & SFLAG_DIBSECTION) {
369 /* Release the DC */
370 SelectObject(This->hDC, This->dib.holdbitmap);
371 DeleteDC(This->hDC);
372 /* Release the DIB section */
373 DeleteObject(This->dib.DIBsection);
374 This->dib.bitmap_data = NULL;
375 This->resource.allocatedMemory = NULL;
377 if(This->Flags & SFLAG_USERPTR) IWineD3DSurface_SetMem(iface, NULL);
379 HeapFree(GetProcessHeap(), 0, This->palette9);
381 IWineD3DResourceImpl_CleanUp((IWineD3DResource *)iface);
382 if(iface == device->ddraw_primary)
383 device->ddraw_primary = NULL;
385 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
386 GL_EXTCALL(glDeleteRenderbuffersEXT(1, &entry->id));
387 HeapFree(GetProcessHeap(), 0, entry);
390 TRACE("(%p) Released\n", This);
391 HeapFree(GetProcessHeap(), 0, This);
394 return ref;
397 /* ****************************************************
398 IWineD3DSurface IWineD3DResource parts follow
399 **************************************************** */
401 void WINAPI IWineD3DSurfaceImpl_PreLoad(IWineD3DSurface *iface) {
402 /* TODO: check for locks */
403 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
404 IWineD3DBaseTexture *baseTexture = NULL;
405 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
407 TRACE("(%p)Checking to see if the container is a base texture\n", This);
408 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
409 TRACE("Passing to container\n");
410 IWineD3DBaseTexture_PreLoad(baseTexture);
411 IWineD3DBaseTexture_Release(baseTexture);
412 } else {
413 TRACE("(%p) : About to load surface\n", This);
415 if(!device->isInDraw) {
416 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
419 ENTER_GL();
420 glEnable(This->glDescription.target);/* make sure texture support is enabled in this context */
421 if (!This->glDescription.level) {
422 if (!This->glDescription.textureName) {
423 glGenTextures(1, &This->glDescription.textureName);
424 checkGLcall("glGenTextures");
425 TRACE("Surface %p given name %d\n", This, This->glDescription.textureName);
427 glBindTexture(This->glDescription.target, This->glDescription.textureName);
428 checkGLcall("glBindTexture");
429 IWineD3DSurface_LoadTexture(iface, FALSE);
430 /* This is where we should be reducing the amount of GLMemoryUsed */
431 } else if (This->glDescription.textureName) { /* NOTE: the level 0 surface of a mpmapped texture must be loaded first! */
432 /* assume this is a coding error not a real error for now */
433 FIXME("Mipmap surface has a glTexture bound to it!\n");
435 if (This->resource.pool == WINED3DPOOL_DEFAULT) {
436 /* Tell opengl to try and keep this texture in video ram (well mostly) */
437 GLclampf tmp;
438 tmp = 0.9f;
439 glPrioritizeTextures(1, &This->glDescription.textureName, &tmp);
441 LEAVE_GL();
443 return;
446 /* ******************************************************
447 IWineD3DSurface IWineD3DSurface parts follow
448 ****************************************************** */
450 void WINAPI IWineD3DSurfaceImpl_SetGlTextureDesc(IWineD3DSurface *iface, UINT textureName, int target) {
451 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
452 TRACE("(%p) : setting textureName %u, target %i\n", This, textureName, target);
453 if (This->glDescription.textureName == 0 && textureName != 0) {
454 IWineD3DSurface_ModifyLocation(iface, SFLAG_INTEXTURE, FALSE);
455 IWineD3DSurface_AddDirtyRect(iface, NULL);
457 This->glDescription.textureName = textureName;
458 This->glDescription.target = target;
459 This->Flags &= ~SFLAG_ALLOCATED;
462 void WINAPI IWineD3DSurfaceImpl_GetGlDesc(IWineD3DSurface *iface, glDescriptor **glDescription) {
463 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
464 TRACE("(%p) : returning %p\n", This, &This->glDescription);
465 *glDescription = &This->glDescription;
468 /* TODO: think about moving this down to resource? */
469 const void *WINAPI IWineD3DSurfaceImpl_GetData(IWineD3DSurface *iface) {
470 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
471 /* This should only be called for sysmem textures, it may be a good idea to extend this to all pools at some point in the future */
472 if (This->resource.pool != WINED3DPOOL_SYSTEMMEM) {
473 FIXME(" (%p)Attempting to get system memory for a non-system memory texture\n", iface);
475 return (CONST void*)(This->resource.allocatedMemory);
478 static void read_from_framebuffer(IWineD3DSurfaceImpl *This, CONST RECT *rect, void *dest, UINT pitch, BOOL srcUpsideDown) {
479 BYTE *mem;
480 GLint fmt;
481 GLint type;
482 BYTE *row, *top, *bottom;
483 int i;
484 BOOL bpp;
486 switch(This->resource.format)
488 case WINED3DFMT_P8:
490 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
491 /* In case of P8 render targets the index is stored in the alpha component */
492 fmt = GL_ALPHA;
493 type = GL_UNSIGNED_BYTE;
494 mem = dest;
495 bpp = This->bytesPerPixel;
496 } else {
497 /* GL can't return palettized data, so read ARGB pixels into a
498 * separate block of memory and convert them into palettized format
499 * in software. Slow, but if the app means to use palettized render
500 * targets and locks it...
502 * Use GL_RGB, GL_UNSIGNED_BYTE to read the surface for performance reasons
503 * Don't use GL_BGR as in the WINED3DFMT_R8G8B8 case, instead watch out
504 * for the color channels when palettizing the colors.
506 fmt = GL_RGB;
507 type = GL_UNSIGNED_BYTE;
508 pitch *= 3;
509 mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * 3);
510 if(!mem) {
511 ERR("Out of memory\n");
512 return;
514 bpp = This->bytesPerPixel * 3;
517 break;
519 default:
520 mem = dest;
521 fmt = This->glDescription.glFormat;
522 type = This->glDescription.glType;
523 bpp = This->bytesPerPixel;
526 if(This->Flags & SFLAG_PBO) {
527 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
528 checkGLcall("glBindBufferARB");
531 glReadPixels(rect->left, rect->top,
532 rect->right - rect->left,
533 rect->bottom - rect->top,
534 fmt, type, mem);
535 vcheckGLcall("glReadPixels");
537 if(This->Flags & SFLAG_PBO) {
538 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
539 checkGLcall("glBindBufferARB");
541 /* Check if we need to flip the image. If we need to flip use glMapBufferARB
542 * to get a pointer to it and perform the flipping in software. This is a lot
543 * faster than calling glReadPixels for each line. In case we want more speed
544 * we should rerender it flipped in a FBO and read the data back from the FBO. */
545 if(!srcUpsideDown) {
546 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
547 checkGLcall("glBindBufferARB");
549 mem = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
550 checkGLcall("glMapBufferARB");
554 /* TODO: Merge this with the palettization loop below for P8 targets */
555 if(!srcUpsideDown) {
556 UINT len, off;
557 /* glReadPixels returns the image upside down, and there is no way to prevent this.
558 Flip the lines in software */
559 len = (rect->right - rect->left) * bpp;
560 off = rect->left * bpp;
562 row = HeapAlloc(GetProcessHeap(), 0, len);
563 if(!row) {
564 ERR("Out of memory\n");
565 if(This->resource.format == WINED3DFMT_P8) HeapFree(GetProcessHeap(), 0, mem);
566 return;
569 top = mem + pitch * rect->top;
570 bottom = ((BYTE *) mem) + pitch * ( rect->bottom - rect->top - 1);
571 for(i = 0; i < (rect->bottom - rect->top) / 2; i++) {
572 memcpy(row, top + off, len);
573 memcpy(top + off, bottom + off, len);
574 memcpy(bottom + off, row, len);
575 top += pitch;
576 bottom -= pitch;
578 HeapFree(GetProcessHeap(), 0, row);
580 /* Unmap the temp PBO buffer */
581 if(This->Flags & SFLAG_PBO) {
582 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
583 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
587 /* For P8 textures we need to perform an inverse palette lookup. This is done by searching for a palette
588 * index which matches the RGB value. Note this isn't guaranteed to work when there are multiple entries for
589 * the same color but we have no choice.
590 * In case of render targets, the index is stored in the alpha component so no conversion is needed.
592 if((This->resource.format == WINED3DFMT_P8) && !(This->resource.usage & WINED3DUSAGE_RENDERTARGET)) {
593 PALETTEENTRY *pal;
594 DWORD width = pitch / 3;
595 int x, y, c;
596 if(This->palette) {
597 pal = This->palette->palents;
598 } else {
599 pal = This->resource.wineD3DDevice->palettes[This->resource.wineD3DDevice->currentPalette];
602 for(y = rect->top; y < rect->bottom; y++) {
603 for(x = rect->left; x < rect->right; x++) {
604 /* start lines pixels */
605 BYTE *blue = (BYTE *) ((BYTE *) mem) + y * pitch + x * (sizeof(BYTE) * 3);
606 BYTE *green = blue + 1;
607 BYTE *red = green + 1;
609 for(c = 0; c < 256; c++) {
610 if(*red == pal[c].peRed &&
611 *green == pal[c].peGreen &&
612 *blue == pal[c].peBlue)
614 *((BYTE *) dest + y * width + x) = c;
615 break;
620 HeapFree(GetProcessHeap(), 0, mem);
624 static HRESULT WINAPI IWineD3DSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags) {
625 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
626 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
627 IWineD3DSwapChainImpl *swapchain = NULL;
629 TRACE("(%p) : rect@%p flags(%08x), output lockedRect@%p, memory@%p\n", This, pRect, Flags, pLockedRect, This->resource.allocatedMemory);
631 if (This->Flags & SFLAG_LOCKED) {
632 WARN("Surface is already locked, returning D3DERR_INVALIDCALL\n");
633 return WINED3DERR_INVALIDCALL;
635 if (!(This->Flags & SFLAG_LOCKABLE)) {
636 /* Note: UpdateTextures calls CopyRects which calls this routine to populate the
637 texture regions, and since the destination is an unlockable region we need
638 to tolerate this */
639 TRACE("Warning: trying to lock unlockable surf@%p\n", This);
640 /*return WINED3DERR_INVALIDCALL; */
643 pLockedRect->Pitch = IWineD3DSurface_GetPitch(iface);
645 /* Mark the surface locked */
646 This->Flags |= SFLAG_LOCKED;
648 /* Whatever surface we have, make sure that there is memory allocated for the downloaded copy,
649 * or a pbo to map
651 if(!(This->resource.allocatedMemory || This->Flags & SFLAG_PBO)) {
652 This->resource.allocatedMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + 4);
653 if(This->Flags & SFLAG_INSYSMEM) {
654 ERR("Surface without memory or pbo has SFLAG_INSYSMEM set!\n");
658 /* Create a PBO for dynamically locked surfaces but don't do it for converted or non-pow2 surfaces.
659 * Also don't create a PBO for systemmem surfaces. */
660 if(GL_SUPPORT(ARB_PIXEL_BUFFER_OBJECT) && (This->Flags & SFLAG_DYNLOCK) && !(This->Flags & (SFLAG_PBO | SFLAG_CONVERTED | SFLAG_NONPOW2)) && (This->resource.pool != WINED3DPOOL_SYSTEMMEM)) {
661 GLenum error;
662 ENTER_GL();
664 GL_EXTCALL(glGenBuffersARB(1, &This->pbo));
665 error = glGetError();
666 if(This->pbo == 0 || error != GL_NO_ERROR) {
667 ERR("Failed to bind the PBO with error %s (%#x)\n", debug_glerror(error), error);
670 TRACE("Attaching pbo=%#x to (%p)\n", This->pbo, This);
672 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
673 checkGLcall("glBindBufferARB");
675 GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->resource.size + 4, This->resource.allocatedMemory, GL_STREAM_DRAW_ARB));
676 checkGLcall("glBufferDataARB");
678 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
679 checkGLcall("glBindBufferARB");
681 /* We don't need the system memory anymore and we can't even use it for PBOs */
682 HeapFree(GetProcessHeap(), 0, This->resource.allocatedMemory);
683 This->resource.allocatedMemory = NULL;
684 This->Flags |= SFLAG_PBO;
685 LEAVE_GL();
688 /* Calculate the correct start address to report */
689 if (NULL == pRect) {
690 This->lockedRect.left = 0;
691 This->lockedRect.top = 0;
692 This->lockedRect.right = This->currentDesc.Width;
693 This->lockedRect.bottom = This->currentDesc.Height;
694 TRACE("Locked Rect (%p) = l %d, t %d, r %d, b %d\n", &This->lockedRect, This->lockedRect.left, This->lockedRect.top, This->lockedRect.right, This->lockedRect.bottom);
695 } else {
696 This->lockedRect.left = pRect->left;
697 This->lockedRect.top = pRect->top;
698 This->lockedRect.right = pRect->right;
699 This->lockedRect.bottom = pRect->bottom;
700 TRACE("Locked Rect (%p) = l %d, t %d, r %d, b %d\n", pRect, pRect->left, pRect->top, pRect->right, pRect->bottom);
703 if (This->Flags & SFLAG_NONPOW2) {
704 TRACE("Locking non-power 2 texture\n");
707 /* Performance optimization: Count how often a surface is locked, if it is locked regularly do not throw away the system memory copy.
708 * This avoids the need to download the surface from opengl all the time. The surface is still downloaded if the opengl texture is
709 * changed
711 if(!(This->Flags & SFLAG_DYNLOCK)) {
712 This->lockCount++;
713 /* MAXLOCKCOUNT is defined in wined3d_private.h */
714 if(This->lockCount > MAXLOCKCOUNT) {
715 TRACE("Surface is locked regularly, not freeing the system memory copy any more\n");
716 This->Flags |= SFLAG_DYNLOCK;
720 if (Flags & WINED3DLOCK_DISCARD) {
721 /* Set SFLAG_INSYSMEM, so we'll never try to download the data from the texture. */
722 TRACE("WINED3DLOCK_DISCARD flag passed, marking local copy as up to date\n");
723 This->Flags |= SFLAG_INSYSMEM;
726 if (This->Flags & SFLAG_INSYSMEM) {
727 TRACE("Local copy is up to date, not downloading data\n");
728 goto lock_end;
731 /* Now download the surface content from opengl
732 * Use the render target readback if the surface is on a swapchain(=onscreen render target) or the current primary target
733 * Offscreen targets which are not active at the moment or are higher targets(fbos) can be locked with the texture path
735 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain);
736 if(swapchain || iface == myDevice->render_targets[0]) {
737 BOOL srcIsUpsideDown;
739 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
740 static BOOL warned = FALSE;
741 if(!warned) {
742 ERR("The application tries to lock the render target, but render target locking is disabled\n");
743 warned = TRUE;
745 if(swapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
746 return WINED3D_OK;
749 /* Activate the surface. Set it up for blitting now, although not necessarily needed for LockRect.
750 * Certain graphics drivers seem to dislike some enabled states when reading from opengl, the blitting usage
751 * should help here. Furthermore unlockrect will need the context set up for blitting. The context manager will find
752 * context->last_was_blit set on the unlock.
754 ActivateContext(myDevice, iface, CTXUSAGE_BLIT);
755 ENTER_GL();
757 /* Select the correct read buffer, and give some debug output.
758 * There is no need to keep track of the current read buffer or reset it, every part of the code
759 * that reads sets the read buffer as desired.
761 if(!swapchain) {
762 /* Locking the primary render target which is not on a swapchain(=offscreen render target).
763 * Read from the back buffer
765 TRACE("Locking offscreen render target\n");
766 glReadBuffer(myDevice->offscreenBuffer);
767 srcIsUpsideDown = TRUE;
768 } else {
769 GLenum buffer = surface_get_gl_buffer(iface, (IWineD3DSwapChain *)swapchain);
770 TRACE("Locking %#x buffer\n", buffer);
771 glReadBuffer(buffer);
772 checkGLcall("glReadBuffer");
774 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
775 srcIsUpsideDown = FALSE;
778 switch(wined3d_settings.rendertargetlock_mode) {
779 case RTL_AUTO:
780 case RTL_READDRAW:
781 case RTL_READTEX:
782 read_from_framebuffer(This, &This->lockedRect, This->resource.allocatedMemory, pLockedRect->Pitch, srcIsUpsideDown);
783 break;
785 case RTL_TEXDRAW:
786 case RTL_TEXTEX:
787 read_from_framebuffer(This, &This->lockedRect, This->resource.allocatedMemory, pLockedRect->Pitch, srcIsUpsideDown);
788 FIXME("Reading from render target with a texture isn't implemented yet, falling back to framebuffer reading\n");
789 break;
792 LEAVE_GL();
794 /* Mark the local copy up to date if a full download was done */
795 if(This->lockedRect.left == 0 &&
796 This->lockedRect.top == 0 &&
797 This->lockedRect.right == This->currentDesc.Width &&
798 This->lockedRect.bottom == This->currentDesc.Height) {
799 This->Flags |= SFLAG_INSYSMEM;
801 } else if(iface == myDevice->stencilBufferTarget) {
802 /** the depth stencil in openGL has a format of GL_FLOAT
803 * which should be good for WINED3DFMT_D16_LOCKABLE
804 * and WINED3DFMT_D16
805 * it is unclear what format the stencil buffer is in except.
806 * 'Each index is converted to fixed point...
807 * If GL_MAP_STENCIL is GL_TRUE, indices are replaced by their
808 * mappings in the table GL_PIXEL_MAP_S_TO_S.
809 * glReadPixels(This->lockedRect.left,
810 * This->lockedRect.bottom - j - 1,
811 * This->lockedRect.right - This->lockedRect.left,
812 * 1,
813 * GL_DEPTH_COMPONENT,
814 * type,
815 * (char *)pLockedRect->pBits + (pLockedRect->Pitch * (j-This->lockedRect.top)));
817 * Depth Stencil surfaces which are not the current depth stencil target should have their data in a
818 * gl texture(next path), or in local memory(early return because of set SFLAG_INSYSMEM above). If
819 * none of that is the case the problem is not in this function :-)
820 ********************************************/
821 FIXME("Depth stencil locking not supported yet\n");
822 } else {
823 /* This path is for normal surfaces, offscreen render targets and everything else that is in a gl texture */
824 TRACE("locking an ordinary surface\n");
826 if (0 != This->glDescription.textureName) {
827 /* Now I have to copy thing bits back */
829 if(myDevice->createParms.BehaviorFlags & WINED3DCREATE_MULTITHREADED) {
830 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
833 ENTER_GL();
834 /* Make sure that a proper texture unit is selected, bind the texture and dirtify the sampler to restore the texture on the next draw */
835 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
836 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
837 checkGLcall("glActiveTextureARB");
839 IWineD3DDeviceImpl_MarkStateDirty(This->resource.wineD3DDevice, STATE_SAMPLER(0));
840 IWineD3DSurface_PreLoad(iface);
842 surface_download_data(This);
843 LEAVE_GL();
847 lock_end:
848 if(This->Flags & SFLAG_PBO) {
849 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
850 ENTER_GL();
851 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
852 checkGLcall("glBindBufferARB");
854 /* This shouldn't happen but could occur if some other function didn't handle the PBO properly */
855 if(This->resource.allocatedMemory) {
856 ERR("The surface already has PBO memory allocated!\n");
859 This->resource.allocatedMemory = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
860 checkGLcall("glMapBufferARB");
862 /* Make sure the pbo isn't set anymore in order not to break non-pbo calls */
863 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
864 checkGLcall("glBindBufferARB");
866 LEAVE_GL();
869 /* Calculate the correct start address to report */
870 if (NULL == pRect) {
871 pLockedRect->pBits = This->resource.allocatedMemory;
872 } else {
873 /* DXTn textures are based on compressed blocks of 4x4 pixels, each
874 * 16 bytes large (8 bytes in case of DXT1). Because of that Pitch has
875 * slightly different meaning compared to regular textures. For DXTn
876 * textures Pitch is the size of a row of blocks, 4 high and "width"
877 * long. The x offset is calculated differently as well, since moving 4
878 * pixels to the right actually moves an entire 4x4 block to right, ie
879 * 16 bytes (8 in case of DXT1). */
880 if (This->resource.format == WINED3DFMT_DXT1) {
881 pLockedRect->pBits = This->resource.allocatedMemory + (pLockedRect->Pitch * pRect->top / 4) + (pRect->left * 2);
882 } else if (This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3
883 || This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) {
884 pLockedRect->pBits = This->resource.allocatedMemory + (pLockedRect->Pitch * pRect->top / 4) + (pRect->left * 4);
885 } else {
886 pLockedRect->pBits = This->resource.allocatedMemory + (pLockedRect->Pitch * pRect->top) + (pRect->left * This->bytesPerPixel);
890 if (Flags & (WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY)) {
891 /* Don't dirtify */
892 } else {
893 IWineD3DBaseTexture *pBaseTexture;
895 * Dirtify on lock
896 * as seen in msdn docs
898 IWineD3DSurface_AddDirtyRect(iface, &This->lockedRect);
900 /** Dirtify Container if needed */
901 if (WINED3D_OK == IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&pBaseTexture) && pBaseTexture != NULL) {
902 TRACE("Making container dirty\n");
903 IWineD3DBaseTexture_SetDirty(pBaseTexture, TRUE);
904 IWineD3DBaseTexture_Release(pBaseTexture);
905 } else {
906 TRACE("Surface is standalone, no need to dirty the container\n");
910 TRACE("returning memory@%p, pitch(%d) dirtyfied(%d)\n", pLockedRect->pBits, pLockedRect->Pitch,
911 This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
912 return WINED3D_OK;
915 static void flush_to_framebuffer_drawpixels(IWineD3DSurfaceImpl *This) {
916 GLint prev_store;
917 GLint prev_rasterpos[4];
918 GLint skipBytes = 0;
919 BOOL storechanged = FALSE, memory_allocated = FALSE;
920 GLint fmt, type;
921 BYTE *mem;
922 UINT bpp;
923 UINT pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This); /* target is argb, 4 byte */
925 glDisable(GL_TEXTURE_2D);
926 vcheckGLcall("glDisable(GL_TEXTURE_2D)");
928 glFlush();
929 vcheckGLcall("glFlush");
930 glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
931 vcheckGLcall("glIntegerv");
932 glGetIntegerv(GL_CURRENT_RASTER_POSITION, &prev_rasterpos[0]);
933 vcheckGLcall("glIntegerv");
934 glPixelZoom(1.0, -1.0);
935 vcheckGLcall("glPixelZoom");
937 /* If not fullscreen, we need to skip a number of bytes to find the next row of data */
938 glGetIntegerv(GL_UNPACK_ROW_LENGTH, &skipBytes);
939 glPixelStorei(GL_UNPACK_ROW_LENGTH, This->currentDesc.Width);
941 glRasterPos3i(This->lockedRect.left, This->lockedRect.top, 1);
942 vcheckGLcall("glRasterPos2f");
944 /* Some drivers(radeon dri, others?) don't like exceptions during
945 * glDrawPixels. If the surface is a DIB section, it might be in GDIMode
946 * after ReleaseDC. Reading it will cause an exception, which x11drv will
947 * catch to put the dib section in InSync mode, which leads to a crash
948 * and a blocked x server on my radeon card.
950 * The following lines read the dib section so it is put in inSync mode
951 * before glDrawPixels is called and the crash is prevented. There won't
952 * be any interfering gdi accesses, because UnlockRect is called from
953 * ReleaseDC, and the app won't use the dc any more afterwards.
955 if((This->Flags & SFLAG_DIBSECTION) && !(This->Flags & SFLAG_PBO)) {
956 volatile BYTE read;
957 read = This->resource.allocatedMemory[0];
960 switch (This->resource.format) {
961 /* No special care needed */
962 case WINED3DFMT_A4R4G4B4:
963 case WINED3DFMT_R5G6B5:
964 case WINED3DFMT_A1R5G5B5:
965 case WINED3DFMT_R8G8B8:
966 type = This->glDescription.glType;
967 fmt = This->glDescription.glFormat;
968 mem = This->resource.allocatedMemory;
969 bpp = This->bytesPerPixel;
970 break;
972 case WINED3DFMT_X4R4G4B4:
974 int size;
975 unsigned short *data;
976 data = (unsigned short *)This->resource.allocatedMemory;
977 size = (This->lockedRect.bottom - This->lockedRect.top) * (This->lockedRect.right - This->lockedRect.left);
978 while(size > 0) {
979 *data |= 0xF000;
980 data++;
981 size--;
983 type = This->glDescription.glType;
984 fmt = This->glDescription.glFormat;
985 mem = This->resource.allocatedMemory;
986 bpp = This->bytesPerPixel;
988 break;
990 case WINED3DFMT_X1R5G5B5:
992 int size;
993 unsigned short *data;
994 data = (unsigned short *)This->resource.allocatedMemory;
995 size = (This->lockedRect.bottom - This->lockedRect.top) * (This->lockedRect.right - This->lockedRect.left);
996 while(size > 0) {
997 *data |= 0x8000;
998 data++;
999 size--;
1001 type = This->glDescription.glType;
1002 fmt = This->glDescription.glFormat;
1003 mem = This->resource.allocatedMemory;
1004 bpp = This->bytesPerPixel;
1006 break;
1008 case WINED3DFMT_X8R8G8B8:
1010 /* make sure the X byte is set to alpha on, since it
1011 could be any random value. This fixes the intro movie in Pirates! */
1012 int size;
1013 unsigned int *data;
1014 data = (unsigned int *)This->resource.allocatedMemory;
1015 size = (This->lockedRect.bottom - This->lockedRect.top) * (This->lockedRect.right - This->lockedRect.left);
1016 while(size > 0) {
1017 *data |= 0xFF000000;
1018 data++;
1019 size--;
1022 /* Fall through */
1024 case WINED3DFMT_A8R8G8B8:
1026 glPixelStorei(GL_PACK_SWAP_BYTES, TRUE);
1027 vcheckGLcall("glPixelStorei");
1028 storechanged = TRUE;
1029 type = This->glDescription.glType;
1030 fmt = This->glDescription.glFormat;
1031 mem = This->resource.allocatedMemory;
1032 bpp = This->bytesPerPixel;
1034 break;
1036 case WINED3DFMT_A2R10G10B10:
1038 glPixelStorei(GL_PACK_SWAP_BYTES, TRUE);
1039 vcheckGLcall("glPixelStorei");
1040 storechanged = TRUE;
1041 type = This->glDescription.glType;
1042 fmt = This->glDescription.glFormat;
1043 mem = This->resource.allocatedMemory;
1044 bpp = This->bytesPerPixel;
1046 break;
1048 case WINED3DFMT_P8:
1050 int height = This->glRect.bottom - This->glRect.top;
1051 type = GL_UNSIGNED_BYTE;
1052 fmt = GL_RGBA;
1054 mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * sizeof(DWORD));
1055 if(!mem) {
1056 ERR("Out of memory\n");
1057 return;
1059 memory_allocated = TRUE;
1060 d3dfmt_convert_surface(This->resource.allocatedMemory,
1061 mem,
1062 pitch,
1063 pitch,
1064 height,
1065 pitch * 4,
1066 CONVERT_PALETTED,
1067 This);
1068 bpp = This->bytesPerPixel * 4;
1069 pitch *= 4;
1071 break;
1073 default:
1074 FIXME("Unsupported Format %u in locking func\n", This->resource.format);
1076 /* Give it a try */
1077 type = This->glDescription.glType;
1078 fmt = This->glDescription.glFormat;
1079 mem = This->resource.allocatedMemory;
1080 bpp = This->bytesPerPixel;
1083 if(This->Flags & SFLAG_PBO) {
1084 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1085 checkGLcall("glBindBufferARB");
1088 glDrawPixels(This->lockedRect.right - This->lockedRect.left,
1089 (This->lockedRect.bottom - This->lockedRect.top)-1,
1090 fmt, type,
1091 mem + bpp * This->lockedRect.left + pitch * This->lockedRect.top);
1092 checkGLcall("glDrawPixels");
1094 if(This->Flags & SFLAG_PBO) {
1095 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1096 checkGLcall("glBindBufferARB");
1099 glPixelZoom(1.0,1.0);
1100 vcheckGLcall("glPixelZoom");
1102 glRasterPos3iv(&prev_rasterpos[0]);
1103 vcheckGLcall("glRasterPos3iv");
1105 /* Reset to previous pack row length */
1106 glPixelStorei(GL_UNPACK_ROW_LENGTH, skipBytes);
1107 vcheckGLcall("glPixelStorei GL_UNPACK_ROW_LENGTH");
1108 if(storechanged) {
1109 glPixelStorei(GL_PACK_SWAP_BYTES, prev_store);
1110 vcheckGLcall("glPixelStorei GL_PACK_SWAP_BYTES");
1113 /* Blitting environment requires that 2D texturing is enabled. It was turned off before,
1114 * turn it on again
1116 glEnable(GL_TEXTURE_2D);
1117 checkGLcall("glEnable(GL_TEXTURE_2D)");
1119 if(memory_allocated) HeapFree(GetProcessHeap(), 0, mem);
1120 return;
1123 static void flush_to_framebuffer_texture(IWineD3DSurfaceImpl *This) {
1124 float glTexCoord[4];
1126 glTexCoord[0] = (float) This->lockedRect.left / (float) This->pow2Width; /* left */
1127 glTexCoord[1] = (float) This->lockedRect.right / (float) This->pow2Width; /* right */
1128 glTexCoord[2] = (float) This->lockedRect.top / (float) This->pow2Height; /* top */
1129 glTexCoord[3] = (float) This->lockedRect.bottom / (float) This->pow2Height; /* bottom */
1131 IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
1133 ENTER_GL();
1135 glBindTexture(GL_TEXTURE_2D, This->glDescription.textureName);
1136 checkGLcall("glEnable glBindTexture");
1138 /* No filtering for blts */
1139 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1140 checkGLcall("glTexParameteri");
1141 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1142 checkGLcall("glTexParameteri");
1144 /* Start drawing a quad */
1145 glBegin(GL_QUADS);
1147 glColor3d(1.0f, 1.0f, 1.0f);
1148 glTexCoord2f(glTexCoord[0], glTexCoord[2]);
1149 glVertex3f(This->lockedRect.left, This->lockedRect.top, 0.0);
1151 glTexCoord2f(glTexCoord[0], glTexCoord[3]);
1152 glVertex3f(This->lockedRect.left, This->lockedRect.bottom, 0.0);
1154 glTexCoord2f(glTexCoord[1], glTexCoord[3]);
1155 glVertex3d(This->lockedRect.right, This->lockedRect.bottom, 0.0);
1157 glTexCoord2f(glTexCoord[1], glTexCoord[2]);
1158 glVertex3f(This->lockedRect.right, This->lockedRect.top, 0.0);
1160 glEnd();
1161 checkGLcall("glEnd");
1163 /* Unbind the texture */
1164 glBindTexture(GL_TEXTURE_2D, 0);
1165 checkGLcall("glEnable glBindTexture");
1167 LEAVE_GL();
1170 static HRESULT WINAPI IWineD3DSurfaceImpl_UnlockRect(IWineD3DSurface *iface) {
1171 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1172 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
1173 IWineD3DSwapChainImpl *swapchain = NULL;
1175 if (!(This->Flags & SFLAG_LOCKED)) {
1176 WARN("trying to Unlock an unlocked surf@%p\n", This);
1177 return WINED3DERR_INVALIDCALL;
1180 if (This->Flags & SFLAG_PBO) {
1181 TRACE("Freeing PBO memory\n");
1182 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
1183 ENTER_GL();
1184 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1185 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1186 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1187 checkGLcall("glUnmapBufferARB");
1188 LEAVE_GL();
1189 This->resource.allocatedMemory = NULL;
1192 TRACE("(%p) : dirtyfied(%d)\n", This, This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
1194 if (This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE)) {
1195 TRACE("(%p) : Not Dirtified so nothing to do, return now\n", This);
1196 goto unlock_end;
1199 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain);
1200 if(swapchain || (myDevice->render_targets && iface == myDevice->render_targets[0])) {
1201 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1202 static BOOL warned = FALSE;
1203 if(!warned) {
1204 ERR("The application tries to write to the render target, but render target locking is disabled\n");
1205 warned = TRUE;
1207 if(swapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
1208 goto unlock_end;
1211 /* Activate the correct context for the render target */
1212 ActivateContext(myDevice, iface, CTXUSAGE_BLIT);
1213 ENTER_GL();
1215 if(!swapchain) {
1216 /* Primary offscreen render target */
1217 TRACE("Offscreen render target\n");
1218 glDrawBuffer(myDevice->offscreenBuffer);
1219 checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
1220 } else {
1221 GLenum buffer = surface_get_gl_buffer(iface, (IWineD3DSwapChain *)swapchain);
1222 TRACE("Unlocking %#x buffer\n", buffer);
1223 glDrawBuffer(buffer);
1224 checkGLcall("glDrawBuffer");
1226 IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapchain);
1229 switch(wined3d_settings.rendertargetlock_mode) {
1230 case RTL_AUTO:
1231 case RTL_READDRAW:
1232 case RTL_TEXDRAW:
1233 flush_to_framebuffer_drawpixels(This);
1234 break;
1236 case RTL_READTEX:
1237 case RTL_TEXTEX:
1238 flush_to_framebuffer_texture(This);
1239 break;
1241 if(!swapchain) {
1242 glDrawBuffer(myDevice->offscreenBuffer);
1243 checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
1244 } else if(swapchain->backBuffer) {
1245 glDrawBuffer(GL_BACK);
1246 checkGLcall("glDrawBuffer(GL_BACK)");
1247 } else {
1248 glDrawBuffer(GL_FRONT);
1249 checkGLcall("glDrawBuffer(GL_FRONT)");
1251 LEAVE_GL();
1253 This->dirtyRect.left = This->currentDesc.Width;
1254 This->dirtyRect.top = This->currentDesc.Height;
1255 This->dirtyRect.right = 0;
1256 This->dirtyRect.bottom = 0;
1257 This->Flags |= SFLAG_INDRAWABLE;
1258 } else if(iface == myDevice->stencilBufferTarget) {
1259 FIXME("Depth Stencil buffer locking is not implemented\n");
1260 } else {
1261 /* The rest should be a normal texture */
1262 IWineD3DBaseTextureImpl *impl;
1263 /* Check if the texture is bound, if yes dirtify the sampler to force a re-upload of the texture
1264 * Can't load the texture here because PreLoad may destroy and recreate the gl texture, so sampler
1265 * states need resetting
1267 if(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&impl) == WINED3D_OK) {
1268 if(impl->baseTexture.bindCount) {
1269 IWineD3DDeviceImpl_MarkStateDirty(myDevice, STATE_SAMPLER(impl->baseTexture.sampler));
1271 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *) impl);
1275 unlock_end:
1276 This->Flags &= ~SFLAG_LOCKED;
1277 memset(&This->lockedRect, 0, sizeof(RECT));
1278 return WINED3D_OK;
1281 HRESULT WINAPI IWineD3DSurfaceImpl_GetDC(IWineD3DSurface *iface, HDC *pHDC) {
1282 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1283 WINED3DLOCKED_RECT lock;
1284 HRESULT hr;
1285 RGBQUAD col[256];
1287 TRACE("(%p)->(%p)\n",This,pHDC);
1289 if(This->Flags & SFLAG_USERPTR) {
1290 ERR("Not supported on surfaces with an application-provided surfaces\n");
1291 return WINEDDERR_NODC;
1294 /* Give more detailed info for ddraw */
1295 if (This->Flags & SFLAG_DCINUSE)
1296 return WINEDDERR_DCALREADYCREATED;
1298 /* Can't GetDC if the surface is locked */
1299 if (This->Flags & SFLAG_LOCKED)
1300 return WINED3DERR_INVALIDCALL;
1302 memset(&lock, 0, sizeof(lock)); /* To be sure */
1304 /* Create a DIB section if there isn't a hdc yet */
1305 if(!This->hDC) {
1306 IWineD3DBaseSurfaceImpl_CreateDIBSection(iface);
1307 if(This->Flags & SFLAG_CLIENT) {
1308 IWineD3DSurface_PreLoad(iface);
1311 /* Use the dib section from now on if we are not using a PBO */
1312 if(!(This->Flags & SFLAG_PBO))
1313 This->resource.allocatedMemory = This->dib.bitmap_data;
1316 /* Lock the surface */
1317 hr = IWineD3DSurface_LockRect(iface,
1318 &lock,
1319 NULL,
1322 if(This->Flags & SFLAG_PBO) {
1323 /* Sync the DIB with the PBO. This can't be done earlier because LockRect activates the allocatedMemory */
1324 memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, This->dib.bitmap_size);
1327 if(FAILED(hr)) {
1328 ERR("IWineD3DSurface_LockRect failed with hr = %08x\n", hr);
1329 /* keep the dib section */
1330 return hr;
1333 if(This->resource.format == WINED3DFMT_P8 ||
1334 This->resource.format == WINED3DFMT_A8P8) {
1335 unsigned int n;
1336 if(This->palette) {
1337 PALETTEENTRY ent[256];
1339 GetPaletteEntries(This->palette->hpal, 0, 256, ent);
1340 for (n=0; n<256; n++) {
1341 col[n].rgbRed = ent[n].peRed;
1342 col[n].rgbGreen = ent[n].peGreen;
1343 col[n].rgbBlue = ent[n].peBlue;
1344 col[n].rgbReserved = 0;
1346 } else {
1347 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1349 for (n=0; n<256; n++) {
1350 col[n].rgbRed = device->palettes[device->currentPalette][n].peRed;
1351 col[n].rgbGreen = device->palettes[device->currentPalette][n].peGreen;
1352 col[n].rgbBlue = device->palettes[device->currentPalette][n].peBlue;
1353 col[n].rgbReserved = 0;
1357 SetDIBColorTable(This->hDC, 0, 256, col);
1360 *pHDC = This->hDC;
1361 TRACE("returning %p\n",*pHDC);
1362 This->Flags |= SFLAG_DCINUSE;
1364 return WINED3D_OK;
1367 HRESULT WINAPI IWineD3DSurfaceImpl_ReleaseDC(IWineD3DSurface *iface, HDC hDC) {
1368 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1370 TRACE("(%p)->(%p)\n",This,hDC);
1372 if (!(This->Flags & SFLAG_DCINUSE))
1373 return WINED3DERR_INVALIDCALL;
1375 if (This->hDC !=hDC) {
1376 WARN("Application tries to release an invalid DC(%p), surface dc is %p\n", hDC, This->hDC);
1377 return WINED3DERR_INVALIDCALL;
1380 if((This->Flags & SFLAG_PBO) && This->resource.allocatedMemory) {
1381 /* Copy the contents of the DIB over to the PBO */
1382 memcpy(This->resource.allocatedMemory, This->dib.bitmap_data, This->dib.bitmap_size);
1385 /* we locked first, so unlock now */
1386 IWineD3DSurface_UnlockRect(iface);
1388 This->Flags &= ~SFLAG_DCINUSE;
1390 return WINED3D_OK;
1393 /* ******************************************************
1394 IWineD3DSurface Internal (No mapping to directx api) parts follow
1395 ****************************************************** */
1397 HRESULT d3dfmt_get_conv(IWineD3DSurfaceImpl *This, BOOL need_alpha_ck, BOOL use_texturing, GLenum *format, GLenum *internal, GLenum *type, CONVERT_TYPES *convert, int *target_bpp, BOOL srgb_mode) {
1398 BOOL colorkey_active = need_alpha_ck && (This->CKeyFlags & WINEDDSD_CKSRCBLT);
1399 const GlPixelFormatDesc *glDesc;
1400 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
1402 /* Default values: From the surface */
1403 *format = glDesc->glFormat;
1404 *internal = srgb_mode?glDesc->glGammaInternal:glDesc->glInternal;
1405 *type = glDesc->glType;
1406 *convert = NO_CONVERSION;
1407 *target_bpp = This->bytesPerPixel;
1409 /* Ok, now look if we have to do any conversion */
1410 switch(This->resource.format) {
1411 case WINED3DFMT_P8:
1412 /* ****************
1413 Paletted Texture
1414 **************** */
1415 /* Use conversion when the paletted texture extension is not available, or when it is available make sure it is used
1416 * for texturing as it won't work for calls like glDraw-/glReadPixels and further also use conversion in case of color keying.
1418 if( !(GL_SUPPORT(EXT_PALETTED_TEXTURE) || GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) || colorkey_active || (!use_texturing && GL_SUPPORT(EXT_PALETTED_TEXTURE)) ) {
1419 *format = GL_RGBA;
1420 *internal = GL_RGBA;
1421 *type = GL_UNSIGNED_BYTE;
1422 *target_bpp = 4;
1423 if(colorkey_active) {
1424 *convert = CONVERT_PALETTED_CK;
1425 } else {
1426 *convert = CONVERT_PALETTED;
1429 else if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
1430 *format = GL_RED;
1431 *internal = GL_RGBA;
1432 *type = GL_UNSIGNED_BYTE;
1433 *target_bpp = 1;
1436 break;
1438 case WINED3DFMT_R3G3B2:
1439 /* **********************
1440 GL_UNSIGNED_BYTE_3_3_2
1441 ********************** */
1442 if (colorkey_active) {
1443 /* This texture format will never be used.. So do not care about color keying
1444 up until the point in time it will be needed :-) */
1445 FIXME(" ColorKeying not supported in the RGB 332 format !\n");
1447 break;
1449 case WINED3DFMT_R5G6B5:
1450 if (colorkey_active) {
1451 *convert = CONVERT_CK_565;
1452 *format = GL_RGBA;
1453 *internal = GL_RGBA;
1454 *type = GL_UNSIGNED_SHORT_5_5_5_1;
1456 break;
1458 case WINED3DFMT_X1R5G5B5:
1459 if (colorkey_active) {
1460 *convert = CONVERT_CK_5551;
1461 *format = GL_BGRA;
1462 *internal = GL_RGBA;
1463 *type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
1465 break;
1467 case WINED3DFMT_R8G8B8:
1468 if (colorkey_active) {
1469 *convert = CONVERT_CK_RGB24;
1470 *format = GL_RGBA;
1471 *internal = GL_RGBA;
1472 *type = GL_UNSIGNED_INT_8_8_8_8;
1473 *target_bpp = 4;
1475 break;
1477 case WINED3DFMT_X8R8G8B8:
1478 if (colorkey_active) {
1479 *convert = CONVERT_RGB32_888;
1480 *format = GL_RGBA;
1481 *internal = GL_RGBA;
1482 *type = GL_UNSIGNED_INT_8_8_8_8;
1484 break;
1486 case WINED3DFMT_V8U8:
1487 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1488 else if(GL_SUPPORT(ATI_ENVMAP_BUMPMAP)) {
1489 *format = GL_DUDV_ATI;
1490 *internal = GL_DU8DV8_ATI;
1491 *type = GL_BYTE;
1492 /* No conversion - Just change the gl type */
1493 break;
1495 *convert = CONVERT_V8U8;
1496 *format = GL_BGR;
1497 *internal = GL_RGB8;
1498 *type = GL_UNSIGNED_BYTE;
1499 *target_bpp = 3;
1500 break;
1502 case WINED3DFMT_L6V5U5:
1503 *convert = CONVERT_L6V5U5;
1504 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1505 *target_bpp = 3;
1506 /* Use format and types from table */
1507 } else {
1508 /* Load it into unsigned R5G6B5, swap L and V channels, and revert that in the shader */
1509 *target_bpp = 2;
1510 *format = GL_RGB;
1511 *internal = GL_RGB5;
1512 *type = GL_UNSIGNED_SHORT_5_6_5;
1514 break;
1516 case WINED3DFMT_X8L8V8U8:
1517 *convert = CONVERT_X8L8V8U8;
1518 *target_bpp = 4;
1519 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1520 /* Use formats from gl table. It is a bit unfortunate, but the conversion
1521 * is needed to set the X format to 255 to get 1.0 for alpha when sampling
1522 * the texture. OpenGL can't use GL_DSDT8_MAG8_NV as internal format with
1523 * the needed type and format parameter, so the internal format contains a
1524 * 4th component, which is returned as alpha
1526 } else {
1527 /* Not supported by GL_ATI_envmap_bumpmap */
1528 *format = GL_BGRA;
1529 *internal = GL_RGB8;
1530 *type = GL_UNSIGNED_INT_8_8_8_8_REV;
1532 break;
1534 case WINED3DFMT_Q8W8V8U8:
1535 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1536 *convert = CONVERT_Q8W8V8U8;
1537 *format = GL_BGRA;
1538 *internal = GL_RGBA8;
1539 *type = GL_UNSIGNED_BYTE;
1540 *target_bpp = 4;
1541 /* Not supported by GL_ATI_envmap_bumpmap */
1542 break;
1544 case WINED3DFMT_V16U16:
1545 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1546 *convert = CONVERT_V16U16;
1547 *format = GL_BGR;
1548 *internal = GL_RGB16_EXT;
1549 *type = GL_UNSIGNED_SHORT;
1550 *target_bpp = 6;
1551 /* What should I do here about GL_ATI_envmap_bumpmap?
1552 * Convert it or allow data loss by loading it into a 8 bit / channel texture?
1554 break;
1556 case WINED3DFMT_A4L4:
1557 /* A4L4 exists as an internal gl format, but for some reason there is not
1558 * format+type combination to load it. Thus convert it to A8L8, then load it
1559 * with A4L4 internal, but A8L8 format+type
1561 *convert = CONVERT_A4L4;
1562 *format = GL_LUMINANCE_ALPHA;
1563 *internal = GL_LUMINANCE4_ALPHA4;
1564 *type = GL_UNSIGNED_BYTE;
1565 *target_bpp = 2;
1566 break;
1568 case WINED3DFMT_R32F:
1569 /* Can be loaded in theory with fmt=GL_RED, type=GL_FLOAT, but this fails. The reason
1570 * is that D3D expects the undefined green, blue and alpha channels to return 1.0
1571 * when sampling, but OpenGL sets green and blue to 0.0 instead. Thus we have to inject
1572 * 1.0 instead.
1574 * The alpha channel defaults to 1.0 in opengl, so nothing has to be done about it.
1576 *convert = CONVERT_R32F;
1577 *format = GL_RGB;
1578 *internal = GL_RGB32F_ARB;
1579 *type = GL_FLOAT;
1580 *target_bpp = 12;
1581 break;
1583 case WINED3DFMT_R16F:
1584 /* Similar to R32F */
1585 *convert = CONVERT_R16F;
1586 *format = GL_RGB;
1587 *internal = GL_RGB16F_ARB;
1588 *type = GL_HALF_FLOAT_ARB;
1589 *target_bpp = 6;
1590 break;
1592 default:
1593 break;
1596 return WINED3D_OK;
1599 HRESULT d3dfmt_convert_surface(BYTE *src, BYTE *dst, UINT pitch, UINT width, UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *This) {
1600 BYTE *source, *dest;
1601 TRACE("(%p)->(%p),(%d,%d,%d,%d,%p)\n", src, dst, pitch, height, outpitch, convert,This);
1603 switch (convert) {
1604 case NO_CONVERSION:
1606 memcpy(dst, src, pitch * height);
1607 break;
1609 case CONVERT_PALETTED:
1610 case CONVERT_PALETTED_CK:
1612 IWineD3DPaletteImpl* pal = This->palette;
1613 BYTE table[256][4];
1614 unsigned int x, y;
1616 if( pal == NULL) {
1617 /* TODO: If we are a sublevel, try to get the palette from level 0 */
1620 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
1622 for (y = 0; y < height; y++)
1624 source = src + pitch * y;
1625 dest = dst + outpitch * y;
1626 /* This is an 1 bpp format, using the width here is fine */
1627 for (x = 0; x < width; x++) {
1628 BYTE color = *source++;
1629 *dest++ = table[color][0];
1630 *dest++ = table[color][1];
1631 *dest++ = table[color][2];
1632 *dest++ = table[color][3];
1636 break;
1638 case CONVERT_CK_565:
1640 /* Converting the 565 format in 5551 packed to emulate color-keying.
1642 Note : in all these conversion, it would be best to average the averaging
1643 pixels to get the color of the pixel that will be color-keyed to
1644 prevent 'color bleeding'. This will be done later on if ever it is
1645 too visible.
1647 Note2: Nvidia documents say that their driver does not support alpha + color keying
1648 on the same surface and disables color keying in such a case
1650 unsigned int x, y;
1651 WORD *Source;
1652 WORD *Dest;
1654 TRACE("Color keyed 565\n");
1656 for (y = 0; y < height; y++) {
1657 Source = (WORD *) (src + y * pitch);
1658 Dest = (WORD *) (dst + y * outpitch);
1659 for (x = 0; x < width; x++ ) {
1660 WORD color = *Source++;
1661 *Dest = ((color & 0xFFC0) | ((color & 0x1F) << 1));
1662 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1663 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1664 *Dest |= 0x0001;
1666 Dest++;
1670 break;
1672 case CONVERT_CK_5551:
1674 /* Converting X1R5G5B5 format to R5G5B5A1 to emulate color-keying. */
1675 unsigned int x, y;
1676 WORD *Source;
1677 WORD *Dest;
1678 TRACE("Color keyed 5551\n");
1679 for (y = 0; y < height; y++) {
1680 Source = (WORD *) (src + y * pitch);
1681 Dest = (WORD *) (dst + y * outpitch);
1682 for (x = 0; x < width; x++ ) {
1683 WORD color = *Source++;
1684 *Dest = color;
1685 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1686 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1687 *Dest |= (1 << 15);
1689 else {
1690 *Dest &= ~(1 << 15);
1692 Dest++;
1696 break;
1698 case CONVERT_V8U8:
1700 unsigned int x, y;
1701 short *Source;
1702 unsigned char *Dest;
1703 for(y = 0; y < height; y++) {
1704 Source = (short *) (src + y * pitch);
1705 Dest = (unsigned char *) (dst + y * outpitch);
1706 for (x = 0; x < width; x++ ) {
1707 long color = (*Source++);
1708 /* B */ Dest[0] = 0xff;
1709 /* G */ Dest[1] = (color >> 8) + 128; /* V */
1710 /* R */ Dest[2] = (color) + 128; /* U */
1711 Dest += 3;
1714 break;
1717 case CONVERT_V16U16:
1719 unsigned int x, y;
1720 DWORD *Source;
1721 unsigned short *Dest;
1722 for(y = 0; y < height; y++) {
1723 Source = (DWORD *) (src + y * pitch);
1724 Dest = (unsigned short *) (dst + y * outpitch);
1725 for (x = 0; x < width; x++ ) {
1726 DWORD color = (*Source++);
1727 /* B */ Dest[0] = 0xffff;
1728 /* G */ Dest[1] = (color >> 16) + 32768; /* V */
1729 /* R */ Dest[2] = (color ) + 32768; /* U */
1730 Dest += 3;
1733 break;
1736 case CONVERT_Q8W8V8U8:
1738 unsigned int x, y;
1739 DWORD *Source;
1740 unsigned char *Dest;
1741 for(y = 0; y < height; y++) {
1742 Source = (DWORD *) (src + y * pitch);
1743 Dest = (unsigned char *) (dst + y * outpitch);
1744 for (x = 0; x < width; x++ ) {
1745 long color = (*Source++);
1746 /* B */ Dest[0] = ((color >> 16) & 0xff) + 128; /* W */
1747 /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
1748 /* R */ Dest[2] = (color & 0xff) + 128; /* U */
1749 /* A */ Dest[3] = ((color >> 24) & 0xff) + 128; /* Q */
1750 Dest += 4;
1753 break;
1756 case CONVERT_L6V5U5:
1758 unsigned int x, y;
1759 WORD *Source;
1760 unsigned char *Dest;
1762 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1763 /* This makes the gl surface bigger(24 bit instead of 16), but it works with
1764 * fixed function and shaders without further conversion once the surface is
1765 * loaded
1767 for(y = 0; y < height; y++) {
1768 Source = (WORD *) (src + y * pitch);
1769 Dest = (unsigned char *) (dst + y * outpitch);
1770 for (x = 0; x < width; x++ ) {
1771 short color = (*Source++);
1772 unsigned char l = ((color >> 10) & 0xfc);
1773 char v = ((color >> 5) & 0x3e);
1774 char u = ((color ) & 0x1f);
1776 /* 8 bits destination, 6 bits source, 8th bit is the sign. gl ignores the sign
1777 * and doubles the positive range. Thus shift left only once, gl does the 2nd
1778 * shift. GL reads a signed value and converts it into an unsigned value.
1780 /* M */ Dest[2] = l << 1;
1782 /* Those are read as signed, but kept signed. Just left-shift 3 times to scale
1783 * from 5 bit values to 8 bit values.
1785 /* V */ Dest[1] = v << 3;
1786 /* U */ Dest[0] = u << 3;
1787 Dest += 3;
1790 } else {
1791 for(y = 0; y < height; y++) {
1792 unsigned short *Dest_s = (unsigned short *) (dst + y * outpitch);
1793 Source = (WORD *) (src + y * pitch);
1794 for (x = 0; x < width; x++ ) {
1795 short color = (*Source++);
1796 unsigned char l = ((color >> 10) & 0xfc);
1797 short v = ((color >> 5) & 0x3e);
1798 short u = ((color ) & 0x1f);
1799 short v_conv = v + 16;
1800 short u_conv = u + 16;
1802 *Dest_s = ((v_conv << 11) & 0xf800) | ((l << 5) & 0x7e0) | (u_conv & 0x1f);
1803 Dest_s += 1;
1807 break;
1810 case CONVERT_X8L8V8U8:
1812 unsigned int x, y;
1813 DWORD *Source;
1814 unsigned char *Dest;
1816 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1817 /* This implementation works with the fixed function pipeline and shaders
1818 * without further modification after converting the surface.
1820 for(y = 0; y < height; y++) {
1821 Source = (DWORD *) (src + y * pitch);
1822 Dest = (unsigned char *) (dst + y * outpitch);
1823 for (x = 0; x < width; x++ ) {
1824 long color = (*Source++);
1825 /* L */ Dest[2] = ((color >> 16) & 0xff); /* L */
1826 /* V */ Dest[1] = ((color >> 8 ) & 0xff); /* V */
1827 /* U */ Dest[0] = (color & 0xff); /* U */
1828 /* I */ Dest[3] = 255; /* X */
1829 Dest += 4;
1832 } else {
1833 /* Doesn't work correctly with the fixed function pipeline, but can work in
1834 * shaders if the shader is adjusted. (There's no use for this format in gl's
1835 * standard fixed function pipeline anyway).
1837 for(y = 0; y < height; y++) {
1838 Source = (DWORD *) (src + y * pitch);
1839 Dest = (unsigned char *) (dst + y * outpitch);
1840 for (x = 0; x < width; x++ ) {
1841 long color = (*Source++);
1842 /* B */ Dest[0] = ((color >> 16) & 0xff); /* L */
1843 /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
1844 /* R */ Dest[2] = (color & 0xff) + 128; /* U */
1845 Dest += 4;
1849 break;
1852 case CONVERT_A4L4:
1854 unsigned int x, y;
1855 unsigned char *Source;
1856 unsigned char *Dest;
1857 for(y = 0; y < height; y++) {
1858 Source = (unsigned char *) (src + y * pitch);
1859 Dest = (unsigned char *) (dst + y * outpitch);
1860 for (x = 0; x < width; x++ ) {
1861 unsigned char color = (*Source++);
1862 /* A */ Dest[1] = (color & 0xf0) << 0;
1863 /* L */ Dest[0] = (color & 0x0f) << 4;
1864 Dest += 2;
1867 break;
1870 case CONVERT_R32F:
1872 unsigned int x, y;
1873 float *Source;
1874 float *Dest;
1875 for(y = 0; y < height; y++) {
1876 Source = (float *) (src + y * pitch);
1877 Dest = (float *) (dst + y * outpitch);
1878 for (x = 0; x < width; x++ ) {
1879 float color = (*Source++);
1880 Dest[0] = color;
1881 Dest[1] = 1.0;
1882 Dest[2] = 1.0;
1883 Dest += 3;
1886 break;
1889 case CONVERT_R16F:
1891 unsigned int x, y;
1892 WORD *Source;
1893 WORD *Dest;
1894 WORD one = 0x3c00;
1895 for(y = 0; y < height; y++) {
1896 Source = (WORD *) (src + y * pitch);
1897 Dest = (WORD *) (dst + y * outpitch);
1898 for (x = 0; x < width; x++ ) {
1899 WORD color = (*Source++);
1900 Dest[0] = color;
1901 Dest[1] = one;
1902 Dest[2] = one;
1903 Dest += 3;
1906 break;
1908 default:
1909 ERR("Unsupported conversation type %d\n", convert);
1911 return WINED3D_OK;
1914 static void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey) {
1915 IWineD3DPaletteImpl* pal = This->palette;
1916 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1917 BOOL index_in_alpha = FALSE;
1918 int i;
1920 /* Old games like StarCraft, C&C, Red Alert and others use P8 render targets.
1921 * Reading back the RGB output each lockrect (each frame as they lock the whole screen)
1922 * is slow. Further RGB->P8 conversion is not possible because palettes can have
1923 * duplicate entries. Store the color key in the unused alpha component to speed the
1924 * download up and to make conversion unneeded. */
1925 if (device->render_targets && device->render_targets[0]) {
1926 IWineD3DSurfaceImpl* render_target = (IWineD3DSurfaceImpl*)device->render_targets[0];
1928 if(render_target->resource.usage & WINED3DUSAGE_RENDERTARGET)
1929 index_in_alpha = TRUE;
1932 if (pal == NULL) {
1933 /* Still no palette? Use the device's palette */
1934 /* Get the surface's palette */
1935 for (i = 0; i < 256; i++) {
1936 table[i][0] = device->palettes[device->currentPalette][i].peRed;
1937 table[i][1] = device->palettes[device->currentPalette][i].peGreen;
1938 table[i][2] = device->palettes[device->currentPalette][i].peBlue;
1940 if(index_in_alpha) {
1941 table[i][3] = i;
1942 } else if (colorkey &&
1943 (i >= This->SrcBltCKey.dwColorSpaceLowValue) &&
1944 (i <= This->SrcBltCKey.dwColorSpaceHighValue)) {
1945 /* We should maybe here put a more 'neutral' color than the standard bright purple
1946 one often used by application to prevent the nice purple borders when bi-linear
1947 filtering is on */
1948 table[i][3] = 0x00;
1949 } else {
1950 table[i][3] = 0xFF;
1953 } else {
1954 TRACE("Using surface palette %p\n", pal);
1955 /* Get the surface's palette */
1956 for (i = 0; i < 256; i++) {
1957 table[i][0] = pal->palents[i].peRed;
1958 table[i][1] = pal->palents[i].peGreen;
1959 table[i][2] = pal->palents[i].peBlue;
1961 if(index_in_alpha) {
1962 table[i][3] = i;
1964 else if (colorkey &&
1965 (i >= This->SrcBltCKey.dwColorSpaceLowValue) &&
1966 (i <= This->SrcBltCKey.dwColorSpaceHighValue)) {
1967 /* We should maybe here put a more 'neutral' color than the standard bright purple
1968 one often used by application to prevent the nice purple borders when bi-linear
1969 filtering is on */
1970 table[i][3] = 0x00;
1971 } else if(pal->Flags & WINEDDPCAPS_ALPHA) {
1972 table[i][3] = pal->palents[i].peFlags;
1973 } else {
1974 table[i][3] = 0xFF;
1980 const char *fragment_palette_conversion =
1981 "!!ARBfp1.0\n"
1982 "TEMP index;\n"
1983 "PARAM constants = { 0.996, 0.00195, 0, 0 };\n" /* { 255/256, 0.5/255*255/256, 0, 0 } */
1984 "TEX index.x, fragment.texcoord[0], texture[0], 2D;\n" /* store the red-component of the current pixel */
1985 "MAD index.x, index.x, constants.x, constants.y;\n" /* Scale the index by 255/256 and add a bias of '0.5' in order to sample in the middle */
1986 "TEX result.color, index, texture[1], 1D;\n" /* use the red-component as a index in the palette to get the final color */
1987 "END";
1989 /* This function is used in case of 8bit paletted textures to upload the palette.
1990 It supports GL_EXT_paletted_texture and GL_ARB_fragment_program, support for other
1991 extensions like ATI_fragment_shaders is possible.
1993 static void d3dfmt_p8_upload_palette(IWineD3DSurface *iface, CONVERT_TYPES convert) {
1994 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1995 BYTE table[256][4];
1996 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1998 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
2000 /* Try to use the paletted texture extension */
2001 if(GL_SUPPORT(EXT_PALETTED_TEXTURE))
2003 TRACE("Using GL_EXT_PALETTED_TEXTURE for 8-bit paletted texture support\n");
2004 GL_EXTCALL(glColorTableEXT(GL_TEXTURE_2D,GL_RGBA,256,GL_RGBA,GL_UNSIGNED_BYTE, table));
2006 else
2008 /* Let a fragment shader do the color conversion by uploading the palette to a 1D texture.
2009 * The 8bit pixel data will be used as an index in this palette texture to retrieve the final color. */
2010 TRACE("Using fragment shaders for emulating 8-bit paletted texture support\n");
2012 /* Create the fragment program if we don't have it */
2013 if(!device->paletteConversionShader)
2015 glEnable(GL_FRAGMENT_PROGRAM_ARB);
2016 GL_EXTCALL(glGenProgramsARB(1, &device->paletteConversionShader));
2017 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, device->paletteConversionShader));
2018 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(fragment_palette_conversion), (const GLbyte *)fragment_palette_conversion));
2019 glDisable(GL_FRAGMENT_PROGRAM_ARB);
2022 glEnable(GL_FRAGMENT_PROGRAM_ARB);
2023 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, device->paletteConversionShader));
2025 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE1));
2026 glEnable(GL_TEXTURE_1D);
2027 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2029 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2030 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); /* Make sure we have discrete color levels. */
2031 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2032 glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, table); /* Upload the palette */
2034 /* Switch back to unit 0 in which the 2D texture will be stored. */
2035 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0));
2037 /* Rebind the texture because it isn't bound anymore */
2038 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2042 static BOOL palette9_changed(IWineD3DSurfaceImpl *This) {
2043 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2045 if(This->palette || (This->resource.format != WINED3DFMT_P8 && This->resource.format != WINED3DFMT_A8P8)) {
2046 /* If a ddraw-style palette is attached assume no d3d9 palette change.
2047 * Also the palette isn't interesting if the surface format isn't P8 or A8P8
2049 return FALSE;
2052 if(This->palette9) {
2053 if(memcmp(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256) == 0) {
2054 return FALSE;
2056 } else {
2057 This->palette9 = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
2059 memcpy(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256);
2060 return TRUE;
2063 static inline void clear_unused_channels(IWineD3DSurfaceImpl *This) {
2064 GLboolean oldwrite[4];
2066 /* Some formats have only some color channels, and the others are 1.0.
2067 * since our rendering renders to all channels, and those pixel formats
2068 * are emulated by using a full texture with the other channels set to 1.0
2069 * manually, clear the unused channels.
2071 * This could be done with hacking colorwriteenable to mask the colors,
2072 * but before drawing the buffer would have to be cleared too, so there's
2073 * no gain in that
2075 switch(This->resource.format) {
2076 case WINED3DFMT_R16F:
2077 case WINED3DFMT_R32F:
2078 TRACE("R16F or R32F format, clearing green, blue and alpha to 1.0\n");
2079 /* Do not activate a context, the correct drawable is active already
2080 * though just the read buffer is set, make sure to have the correct draw
2081 * buffer too
2083 glDrawBuffer(This->resource.wineD3DDevice->offscreenBuffer);
2084 glDisable(GL_SCISSOR_TEST);
2085 glGetBooleanv(GL_COLOR_WRITEMASK, oldwrite);
2086 glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_TRUE);
2087 glClearColor(0.0, 1.0, 1.0, 1.0);
2088 glClear(GL_COLOR_BUFFER_BIT);
2089 glColorMask(oldwrite[0], oldwrite[1], oldwrite[2], oldwrite[3]);
2090 if(!This->resource.wineD3DDevice->render_offscreen) glDrawBuffer(GL_BACK);
2091 checkGLcall("Unused channel clear\n");
2092 break;
2094 default: break;
2098 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadTexture(IWineD3DSurface *iface, BOOL srgb_mode) {
2099 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2100 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2101 GLenum format, internal, type;
2102 CONVERT_TYPES convert;
2103 int bpp;
2104 int width, pitch, outpitch;
2105 BYTE *mem;
2107 if (!(This->Flags & SFLAG_INTEXTURE)) {
2108 TRACE("Reloading because surface is dirty\n");
2109 } else if(/* Reload: gl texture has ck, now no ckey is set OR */
2110 ((This->Flags & SFLAG_GLCKEY) && (!(This->CKeyFlags & WINEDDSD_CKSRCBLT))) ||
2111 /* Reload: vice versa OR */
2112 ((!(This->Flags & SFLAG_GLCKEY)) && (This->CKeyFlags & WINEDDSD_CKSRCBLT)) ||
2113 /* Also reload: Color key is active AND the color key has changed */
2114 ((This->CKeyFlags & WINEDDSD_CKSRCBLT) && (
2115 (This->glCKey.dwColorSpaceLowValue != This->SrcBltCKey.dwColorSpaceLowValue) ||
2116 (This->glCKey.dwColorSpaceHighValue != This->SrcBltCKey.dwColorSpaceHighValue)))) {
2117 TRACE("Reloading because of color keying\n");
2118 } else if(palette9_changed(This)) {
2119 TRACE("Reloading surface because the d3d8/9 palette was changed\n");
2120 } else {
2121 TRACE("surface is already in texture\n");
2122 return WINED3D_OK;
2125 This->Flags |= SFLAG_INTEXTURE;
2127 /* Resources are placed in system RAM and do not need to be recreated when a device is lost.
2128 * These resources are not bound by device size or format restrictions. Because of this,
2129 * these resources cannot be accessed by the Direct3D device nor set as textures or render targets.
2130 * However, these resources can always be created, locked, and copied.
2132 if (This->resource.pool == WINED3DPOOL_SCRATCH )
2134 FIXME("(%p) Operation not supported for scratch textures\n",This);
2135 return WINED3DERR_INVALIDCALL;
2138 d3dfmt_get_conv(This, TRUE /* We need color keying */, TRUE /* We will use textures */, &format, &internal, &type, &convert, &bpp, srgb_mode);
2140 if (This->Flags & SFLAG_INDRAWABLE) {
2141 if (This->resource.format == WINED3DFMT_P8 || This->resource.format == WINED3DFMT_A8P8 ||
2142 This->resource.format == WINED3DFMT_DXT1 || This->resource.format == WINED3DFMT_DXT2 ||
2143 This->resource.format == WINED3DFMT_DXT3 || This->resource.format == WINED3DFMT_DXT4 ||
2144 This->resource.format == WINED3DFMT_DXT5)
2145 FIXME("Format %d not supported\n", This->resource.format);
2146 else {
2147 GLint prevRead;
2149 ENTER_GL();
2150 glGetIntegerv(GL_READ_BUFFER, &prevRead);
2151 vcheckGLcall("glGetIntegerv");
2152 glReadBuffer(This->resource.wineD3DDevice->offscreenBuffer);
2153 vcheckGLcall("glReadBuffer");
2155 if(!(This->Flags & SFLAG_ALLOCATED)) {
2156 surface_allocate_surface(This, internal, This->pow2Width,
2157 This->pow2Height, format, type);
2160 clear_unused_channels(This);
2162 glCopyTexSubImage2D(This->glDescription.target,
2163 This->glDescription.level,
2164 0, 0, 0, 0,
2165 This->currentDesc.Width,
2166 This->currentDesc.Height);
2167 checkGLcall("glCopyTexSubImage2D");
2169 glReadBuffer(prevRead);
2170 vcheckGLcall("glReadBuffer");
2172 LEAVE_GL();
2174 TRACE("Updated target %d\n", This->glDescription.target);
2176 return WINED3D_OK;
2177 } else
2178 /* The only place where LoadTexture() might get called when isInDraw=1
2179 * is ActivateContext where lastActiveRenderTarget is preloaded.
2181 if(iface == device->lastActiveRenderTarget && device->isInDraw)
2182 ERR("Reading back render target but SFLAG_INDRAWABLE not set\n");
2184 /* Otherwise: System memory copy must be most up to date */
2186 if(This->CKeyFlags & WINEDDSD_CKSRCBLT) {
2187 This->Flags |= SFLAG_GLCKEY;
2188 This->glCKey = This->SrcBltCKey;
2190 else This->Flags &= ~SFLAG_GLCKEY;
2192 /* The width is in 'length' not in bytes */
2193 width = This->currentDesc.Width;
2194 pitch = IWineD3DSurface_GetPitch(iface);
2196 if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
2197 int height = This->currentDesc.Height;
2199 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
2200 outpitch = width * bpp;
2201 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
2203 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
2204 if(!mem) {
2205 ERR("Out of memory %d, %d!\n", outpitch, height);
2206 return WINED3DERR_OUTOFVIDEOMEMORY;
2208 d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
2210 This->Flags |= SFLAG_CONVERTED;
2211 } else if( (This->resource.format == WINED3DFMT_P8) && (GL_SUPPORT(EXT_PALETTED_TEXTURE) || GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) ) {
2212 d3dfmt_p8_upload_palette(iface, convert);
2213 This->Flags &= ~SFLAG_CONVERTED;
2214 mem = This->resource.allocatedMemory;
2215 } else {
2216 This->Flags &= ~SFLAG_CONVERTED;
2217 mem = This->resource.allocatedMemory;
2220 /* Make sure the correct pitch is used */
2221 glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
2223 if ((This->Flags & SFLAG_NONPOW2) && !(This->Flags & SFLAG_OVERSIZE)) {
2224 TRACE("non power of two support\n");
2225 if(!(This->Flags & SFLAG_ALLOCATED)) {
2226 surface_allocate_surface(This, internal, This->pow2Width, This->pow2Height, format, type);
2228 if (mem || (This->Flags & SFLAG_PBO)) {
2229 surface_upload_data(This, internal, This->currentDesc.Width, This->currentDesc.Height, format, type, mem);
2231 } else {
2232 /* When making the realloc conditional, keep in mind that GL_APPLE_client_storage may be in use, and This->resource.allocatedMemory
2233 * changed. So also keep track of memory changes. In this case the texture has to be reallocated
2235 if(!(This->Flags & SFLAG_ALLOCATED)) {
2236 surface_allocate_surface(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type);
2238 if (mem || (This->Flags & SFLAG_PBO)) {
2239 surface_upload_data(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type, mem);
2243 /* Restore the default pitch */
2244 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
2246 /* Don't delete PBO memory */
2247 if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
2248 HeapFree(GetProcessHeap(), 0, mem);
2250 #if 0
2252 static unsigned int gen = 0;
2253 char buffer[4096];
2254 ++gen;
2255 if ((gen % 10) == 0) {
2256 snprintf(buffer, sizeof(buffer), "/tmp/surface%p_type%u_level%u_%u.ppm", This, This->glDescription.target, This->glDescription.level, gen);
2257 IWineD3DSurfaceImpl_SaveSnapshot(iface, buffer);
2260 * debugging crash code
2261 if (gen == 250) {
2262 void** test = NULL;
2263 *test = 0;
2267 #endif
2269 if (!(This->Flags & SFLAG_DONOTFREE)) {
2270 HeapFree(GetProcessHeap(), 0, This->resource.allocatedMemory);
2271 This->resource.allocatedMemory = NULL;
2272 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, FALSE);
2275 return WINED3D_OK;
2278 #include <errno.h>
2279 #include <stdio.h>
2280 HRESULT WINAPI IWineD3DSurfaceImpl_SaveSnapshot(IWineD3DSurface *iface, const char* filename) {
2281 FILE* f = NULL;
2282 UINT i, y;
2283 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2284 char *allocatedMemory;
2285 char *textureRow;
2286 IWineD3DSwapChain *swapChain = NULL;
2287 int width, height;
2288 GLuint tmpTexture = 0;
2289 DWORD color;
2290 /*FIXME:
2291 Textures may not be stored in ->allocatedgMemory and a GlTexture
2292 so we should lock the surface before saving a snapshot, or at least check that
2294 /* TODO: Compressed texture images can be obtained from the GL in uncompressed form
2295 by calling GetTexImage and in compressed form by calling
2296 GetCompressedTexImageARB. Queried compressed images can be saved and
2297 later reused by calling CompressedTexImage[123]DARB. Pre-compressed
2298 texture images do not need to be processed by the GL and should
2299 significantly improve texture loading performance relative to uncompressed
2300 images. */
2302 /* Setup the width and height to be the internal texture width and height. */
2303 width = This->pow2Width;
2304 height = This->pow2Height;
2305 /* check to see if we're a 'virtual' texture, e.g. we're not a pbuffer of texture, we're a back buffer*/
2306 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapChain);
2308 if (This->Flags & SFLAG_INDRAWABLE && !(This->Flags & SFLAG_INTEXTURE)) {
2309 /* if were not a real texture then read the back buffer into a real texture */
2310 /* we don't want to interfere with the back buffer so read the data into a temporary
2311 * texture and then save the data out of the temporary texture
2313 GLint prevRead;
2314 ENTER_GL();
2315 TRACE("(%p) Reading render target into texture\n", This);
2316 glEnable(GL_TEXTURE_2D);
2318 glGenTextures(1, &tmpTexture);
2319 glBindTexture(GL_TEXTURE_2D, tmpTexture);
2321 glTexImage2D(GL_TEXTURE_2D,
2323 GL_RGBA,
2324 width,
2325 height,
2326 0/*border*/,
2327 GL_RGBA,
2328 GL_UNSIGNED_INT_8_8_8_8_REV,
2329 NULL);
2331 glGetIntegerv(GL_READ_BUFFER, &prevRead);
2332 vcheckGLcall("glGetIntegerv");
2333 glReadBuffer(swapChain ? GL_BACK : This->resource.wineD3DDevice->offscreenBuffer);
2334 vcheckGLcall("glReadBuffer");
2335 glCopyTexImage2D(GL_TEXTURE_2D,
2337 GL_RGBA,
2340 width,
2341 height,
2344 checkGLcall("glCopyTexImage2D");
2345 glReadBuffer(prevRead);
2346 LEAVE_GL();
2348 } else { /* bind the real texture, and make sure it up to date */
2349 IWineD3DSurface_PreLoad(iface);
2351 allocatedMemory = HeapAlloc(GetProcessHeap(), 0, width * height * 4);
2352 ENTER_GL();
2353 FIXME("Saving texture level %d width %d height %d\n", This->glDescription.level, width, height);
2354 glGetTexImage(GL_TEXTURE_2D,
2355 This->glDescription.level,
2356 GL_RGBA,
2357 GL_UNSIGNED_INT_8_8_8_8_REV,
2358 allocatedMemory);
2359 checkGLcall("glTexImage2D");
2360 if (tmpTexture) {
2361 glBindTexture(GL_TEXTURE_2D, 0);
2362 glDeleteTextures(1, &tmpTexture);
2364 LEAVE_GL();
2366 f = fopen(filename, "w+");
2367 if (NULL == f) {
2368 ERR("opening of %s failed with: %s\n", filename, strerror(errno));
2369 return WINED3DERR_INVALIDCALL;
2371 /* Save the data out to a TGA file because 1: it's an easy raw format, 2: it supports an alpha channel */
2372 TRACE("(%p) opened %s with format %s\n", This, filename, debug_d3dformat(This->resource.format));
2373 /* TGA header */
2374 fputc(0,f);
2375 fputc(0,f);
2376 fputc(2,f);
2377 fputc(0,f);
2378 fputc(0,f);
2379 fputc(0,f);
2380 fputc(0,f);
2381 fputc(0,f);
2382 fputc(0,f);
2383 fputc(0,f);
2384 fputc(0,f);
2385 fputc(0,f);
2386 /* short width*/
2387 fwrite(&width,2,1,f);
2388 /* short height */
2389 fwrite(&height,2,1,f);
2390 /* format rgba */
2391 fputc(0x20,f);
2392 fputc(0x28,f);
2393 /* raw data */
2394 /* if the data is upside down if we've fetched it from a back buffer, so it needs flipping again to make it the correct way up */
2395 if(swapChain)
2396 textureRow = allocatedMemory + (width * (height - 1) *4);
2397 else
2398 textureRow = allocatedMemory;
2399 for (y = 0 ; y < height; y++) {
2400 for (i = 0; i < width; i++) {
2401 color = *((DWORD*)textureRow);
2402 fputc((color >> 16) & 0xFF, f); /* B */
2403 fputc((color >> 8) & 0xFF, f); /* G */
2404 fputc((color >> 0) & 0xFF, f); /* R */
2405 fputc((color >> 24) & 0xFF, f); /* A */
2406 textureRow += 4;
2408 /* take two rows of the pointer to the texture memory */
2409 if(swapChain)
2410 (textureRow-= width << 3);
2413 TRACE("Closing file\n");
2414 fclose(f);
2416 if(swapChain) {
2417 IWineD3DSwapChain_Release(swapChain);
2419 HeapFree(GetProcessHeap(), 0, allocatedMemory);
2420 return WINED3D_OK;
2424 * Slightly inefficient way to handle multiple dirty rects but it works :)
2426 extern HRESULT WINAPI IWineD3DSurfaceImpl_AddDirtyRect(IWineD3DSurface *iface, CONST RECT* pDirtyRect) {
2427 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2428 IWineD3DBaseTexture *baseTexture = NULL;
2429 if (!(This->Flags & SFLAG_INSYSMEM) && (This->Flags & SFLAG_INTEXTURE))
2430 surface_download_data(This);
2432 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2433 if (NULL != pDirtyRect) {
2434 This->dirtyRect.left = min(This->dirtyRect.left, pDirtyRect->left);
2435 This->dirtyRect.top = min(This->dirtyRect.top, pDirtyRect->top);
2436 This->dirtyRect.right = max(This->dirtyRect.right, pDirtyRect->right);
2437 This->dirtyRect.bottom = max(This->dirtyRect.bottom, pDirtyRect->bottom);
2438 } else {
2439 This->dirtyRect.left = 0;
2440 This->dirtyRect.top = 0;
2441 This->dirtyRect.right = This->currentDesc.Width;
2442 This->dirtyRect.bottom = This->currentDesc.Height;
2444 TRACE("(%p) : Dirty: yes, Rect:(%d,%d,%d,%d)\n", This, This->dirtyRect.left,
2445 This->dirtyRect.top, This->dirtyRect.right, This->dirtyRect.bottom);
2446 /* if the container is a basetexture then mark it dirty. */
2447 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
2448 TRACE("Passing to container\n");
2449 IWineD3DBaseTexture_SetDirty(baseTexture, TRUE);
2450 IWineD3DBaseTexture_Release(baseTexture);
2452 return WINED3D_OK;
2455 HRESULT WINAPI IWineD3DSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format) {
2456 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2457 HRESULT hr;
2458 const GlPixelFormatDesc *glDesc;
2459 getFormatDescEntry(format, &GLINFO_LOCATION, &glDesc);
2461 TRACE("(%p) : Calling base function first\n", This);
2462 hr = IWineD3DBaseSurfaceImpl_SetFormat(iface, format);
2463 if(SUCCEEDED(hr)) {
2464 /* Setup some glformat defaults */
2465 This->glDescription.glFormat = glDesc->glFormat;
2466 This->glDescription.glFormatInternal = glDesc->glInternal;
2467 This->glDescription.glType = glDesc->glType;
2469 This->Flags &= ~SFLAG_ALLOCATED;
2470 TRACE("(%p) : glFormat %d, glFotmatInternal %d, glType %d\n", This,
2471 This->glDescription.glFormat, This->glDescription.glFormatInternal, This->glDescription.glType);
2473 return hr;
2476 HRESULT WINAPI IWineD3DSurfaceImpl_SetMem(IWineD3DSurface *iface, void *Mem) {
2477 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
2479 if(This->Flags & (SFLAG_LOCKED | SFLAG_DCINUSE)) {
2480 WARN("Surface is locked or the HDC is in use\n");
2481 return WINED3DERR_INVALIDCALL;
2484 if(Mem && Mem != This->resource.allocatedMemory) {
2485 void *release = NULL;
2487 /* Do I have to copy the old surface content? */
2488 if(This->Flags & SFLAG_DIBSECTION) {
2489 /* Release the DC. No need to hold the critical section for the update
2490 * Thread because this thread runs only on front buffers, but this method
2491 * fails for render targets in the check above.
2493 SelectObject(This->hDC, This->dib.holdbitmap);
2494 DeleteDC(This->hDC);
2495 /* Release the DIB section */
2496 DeleteObject(This->dib.DIBsection);
2497 This->dib.bitmap_data = NULL;
2498 This->resource.allocatedMemory = NULL;
2499 This->hDC = NULL;
2500 This->Flags &= ~SFLAG_DIBSECTION;
2501 } else if(!(This->Flags & SFLAG_USERPTR)) {
2502 release = This->resource.allocatedMemory;
2504 This->resource.allocatedMemory = Mem;
2505 This->Flags |= SFLAG_USERPTR | SFLAG_INSYSMEM;
2507 /* Now the surface memory is most up do date. Invalidate drawable and texture */
2508 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2510 /* For client textures opengl has to be notified */
2511 if(This->Flags & SFLAG_CLIENT) {
2512 This->Flags &= ~SFLAG_ALLOCATED;
2513 IWineD3DSurface_PreLoad(iface);
2514 /* And hope that the app behaves correctly and did not free the old surface memory before setting a new pointer */
2517 /* Now free the old memory if any */
2518 HeapFree(GetProcessHeap(), 0, release);
2519 } else if(This->Flags & SFLAG_USERPTR) {
2520 /* Lockrect and GetDC will re-create the dib section and allocated memory */
2521 This->resource.allocatedMemory = NULL;
2522 This->Flags &= ~SFLAG_USERPTR;
2524 if(This->Flags & SFLAG_CLIENT) {
2525 This->Flags &= ~SFLAG_ALLOCATED;
2526 /* This respecifies an empty texture and opengl knows that the old memory is gone */
2527 IWineD3DSurface_PreLoad(iface);
2530 return WINED3D_OK;
2533 static HRESULT WINAPI IWineD3DSurfaceImpl_Flip(IWineD3DSurface *iface, IWineD3DSurface *override, DWORD Flags) {
2534 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2535 IWineD3DSwapChainImpl *swapchain = NULL;
2536 HRESULT hr;
2537 TRACE("(%p)->(%p,%x)\n", This, override, Flags);
2539 /* Flipping is only supported on RenderTargets */
2540 if( !(This->resource.usage & WINED3DUSAGE_RENDERTARGET) ) return WINEDDERR_NOTFLIPPABLE;
2542 if(override) {
2543 /* DDraw sets this for the X11 surfaces, so don't confuse the user
2544 * FIXME("(%p) Target override is not supported by now\n", This);
2545 * Additionally, it isn't really possible to support triple-buffering
2546 * properly on opengl at all
2550 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **) &swapchain);
2551 if(!swapchain) {
2552 ERR("Flipped surface is not on a swapchain\n");
2553 return WINEDDERR_NOTFLIPPABLE;
2556 /* Just overwrite the swapchain presentation interval. This is ok because only ddraw apps can call Flip,
2557 * and only d3d8 and d3d9 apps specify the presentation interval
2559 if((Flags & (WINEDDFLIP_NOVSYNC | WINEDDFLIP_INTERVAL2 | WINEDDFLIP_INTERVAL3 | WINEDDFLIP_INTERVAL4)) == 0) {
2560 /* Most common case first to avoid wasting time on all the other cases */
2561 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_ONE;
2562 } else if(Flags & WINEDDFLIP_NOVSYNC) {
2563 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
2564 } else if(Flags & WINEDDFLIP_INTERVAL2) {
2565 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_TWO;
2566 } else if(Flags & WINEDDFLIP_INTERVAL3) {
2567 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_THREE;
2568 } else {
2569 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_FOUR;
2572 /* Flipping a OpenGL surface -> Use WineD3DDevice::Present */
2573 hr = IWineD3DSwapChain_Present((IWineD3DSwapChain *) swapchain, NULL, NULL, 0, NULL, 0);
2574 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
2575 return hr;
2578 /* Does a direct frame buffer -> texture copy. Stretching is done
2579 * with single pixel copy calls
2581 static inline void fb_copy_to_texture_direct(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface, IWineD3DSwapChainImpl *swapchain, WINED3DRECT *srect, WINED3DRECT *drect, BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter) {
2582 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2583 float xrel, yrel;
2584 UINT row;
2585 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2588 ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
2589 ENTER_GL();
2590 IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
2592 /* Bind the target texture */
2593 glBindTexture(GL_TEXTURE_2D, This->glDescription.textureName);
2594 checkGLcall("glBindTexture");
2595 if(!swapchain) {
2596 glReadBuffer(myDevice->offscreenBuffer);
2597 } else {
2598 GLenum buffer = surface_get_gl_buffer(SrcSurface, (IWineD3DSwapChain *)swapchain);
2599 glReadBuffer(buffer);
2601 checkGLcall("glReadBuffer");
2603 xrel = (float) (srect->x2 - srect->x1) / (float) (drect->x2 - drect->x1);
2604 yrel = (float) (srect->y2 - srect->y1) / (float) (drect->y2 - drect->y1);
2606 if( (xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) {
2607 FIXME("Doing a pixel by pixel copy from the framebuffer to a texture, expect major performance issues\n");
2609 if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
2610 ERR("Texture filtering not supported in direct blit\n");
2612 } else if((Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) && ((yrel - 1.0 < -eps) || (yrel - 1.0 > eps))) {
2613 ERR("Texture filtering not supported in direct blit\n");
2616 if(upsidedown &&
2617 !((xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) &&
2618 !((yrel - 1.0 < -eps) || (yrel - 1.0 > eps))) {
2619 /* Upside down copy without stretching is nice, one glCopyTexSubImage call will do */
2621 glCopyTexSubImage2D(This->glDescription.target,
2622 This->glDescription.level,
2623 drect->x1, drect->y1, /* xoffset, yoffset */
2624 srect->x1, Src->currentDesc.Height - srect->y2,
2625 drect->x2 - drect->x1, drect->y2 - drect->y1);
2626 } else {
2627 UINT yoffset = Src->currentDesc.Height - srect->y1 + drect->y1 - 1;
2628 /* I have to process this row by row to swap the image,
2629 * otherwise it would be upside down, so stretching in y direction
2630 * doesn't cost extra time
2632 * However, stretching in x direction can be avoided if not necessary
2634 for(row = drect->y1; row < drect->y2; row++) {
2635 if( (xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) {
2636 /* Well, that stuff works, but it's very slow.
2637 * find a better way instead
2639 UINT col;
2641 for(col = drect->x1; col < drect->x2; col++) {
2642 glCopyTexSubImage2D(This->glDescription.target,
2643 This->glDescription.level,
2644 drect->x1 + col, row, /* xoffset, yoffset */
2645 srect->x1 + col * xrel, yoffset - (int) (row * yrel),
2646 1, 1);
2648 } else {
2649 glCopyTexSubImage2D(This->glDescription.target,
2650 This->glDescription.level,
2651 drect->x1, row, /* xoffset, yoffset */
2652 srect->x1, yoffset - (int) (row * yrel),
2653 drect->x2-drect->x1, 1);
2658 vcheckGLcall("glCopyTexSubImage2D");
2659 LEAVE_GL();
2662 /* Uses the hardware to stretch and flip the image */
2663 static inline void fb_copy_to_texture_hwstretch(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface, IWineD3DSwapChainImpl *swapchain, WINED3DRECT *srect, WINED3DRECT *drect, BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter) {
2664 GLuint src, backup = 0;
2665 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2666 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2667 float left, right, top, bottom; /* Texture coordinates */
2668 UINT fbwidth = Src->currentDesc.Width;
2669 UINT fbheight = Src->currentDesc.Height;
2670 GLenum drawBuffer = GL_BACK;
2672 TRACE("Using hwstretch blit\n");
2673 /* Activate the Proper context for reading from the source surface, set it up for blitting */
2674 ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
2675 ENTER_GL();
2676 IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
2678 /* Try to use an aux buffer for drawing the rectangle. This way it doesn't need restoring.
2679 * This way we don't have to wait for the 2nd readback to finish to leave this function.
2681 if(GL_LIMITS(aux_buffers) >= 2) {
2682 /* Got more than one aux buffer? Use the 2nd aux buffer */
2683 drawBuffer = GL_AUX1;
2684 } else if((swapchain || myDevice->offscreenBuffer == GL_BACK) && GL_LIMITS(aux_buffers) >= 1) {
2685 /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
2686 drawBuffer = GL_AUX0;
2689 if(!swapchain && wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2690 glGenTextures(1, &backup);
2691 checkGLcall("glGenTextures\n");
2692 glBindTexture(GL_TEXTURE_2D, backup);
2693 checkGLcall("glBindTexture(Src->glDescription.target, Src->glDescription.textureName)");
2694 } else {
2695 /* Backup the back buffer and copy the source buffer into a texture to draw an upside down stretched quad. If
2696 * we are reading from the back buffer, the backup can be used as source texture
2698 if(Src->glDescription.textureName == 0) {
2699 /* Get it a description */
2700 IWineD3DSurface_PreLoad(SrcSurface);
2702 glBindTexture(GL_TEXTURE_2D, Src->glDescription.textureName);
2703 checkGLcall("glBindTexture(Src->glDescription.target, Src->glDescription.textureName)");
2705 /* For now invalidate the texture copy of the back buffer. Drawable and sysmem copy are untouched */
2706 Src->Flags &= ~SFLAG_INTEXTURE;
2709 glReadBuffer(GL_BACK);
2710 checkGLcall("glReadBuffer(GL_BACK)");
2712 /* TODO: Only back up the part that will be overwritten */
2713 glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
2714 0, 0 /* read offsets */,
2715 0, 0,
2716 fbwidth,
2717 fbheight);
2719 checkGLcall("glCopyTexSubImage2D");
2721 /* No issue with overriding these - the sampler is dirty due to blit usage */
2722 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
2723 stateLookup[WINELOOKUP_MAGFILTER][Filter - minLookup[WINELOOKUP_MAGFILTER]]);
2724 checkGLcall("glTexParameteri");
2725 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
2726 minMipLookup[Filter][WINED3DTEXF_NONE]);
2727 checkGLcall("glTexParameteri");
2729 if(!swapchain || (IWineD3DSurface *) Src == swapchain->backBuffer[0]) {
2730 src = backup ? backup : Src->glDescription.textureName;
2731 } else {
2732 glReadBuffer(GL_FRONT);
2733 checkGLcall("glReadBuffer(GL_FRONT)");
2735 glGenTextures(1, &src);
2736 checkGLcall("glGenTextures(1, &src)");
2737 glBindTexture(GL_TEXTURE_2D, src);
2738 checkGLcall("glBindTexture(GL_TEXTURE_2D, src)");
2740 /* TODO: Only copy the part that will be read. Use srect->x1, srect->y2 as origin, but with the width watch
2741 * out for power of 2 sizes
2743 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Src->pow2Width, Src->pow2Height, 0,
2744 GL_RGBA, GL_UNSIGNED_BYTE, NULL);
2745 checkGLcall("glTexImage2D");
2746 glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
2747 0, 0 /* read offsets */,
2748 0, 0,
2749 fbwidth,
2750 fbheight);
2752 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2753 checkGLcall("glTexParameteri");
2754 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2755 checkGLcall("glTexParameteri");
2757 glReadBuffer(GL_BACK);
2758 checkGLcall("glReadBuffer(GL_BACK)");
2760 checkGLcall("glEnd and previous");
2762 left = (float) srect->x1 / (float) Src->pow2Width;
2763 right = (float) srect->x2 / (float) Src->pow2Width;
2765 if(upsidedown) {
2766 top = (float) (Src->currentDesc.Height - srect->y1) / (float) Src->pow2Height;
2767 bottom = (float) (Src->currentDesc.Height - srect->y2) / (float) Src->pow2Height;
2768 } else {
2769 top = (float) (Src->currentDesc.Height - srect->y2) / (float) Src->pow2Height;
2770 bottom = (float) (Src->currentDesc.Height - srect->y1) / (float) Src->pow2Height;
2773 /* draw the source texture stretched and upside down. The correct surface is bound already */
2774 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
2775 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
2777 glDrawBuffer(drawBuffer);
2778 glReadBuffer(drawBuffer);
2780 glBegin(GL_QUADS);
2781 /* bottom left */
2782 glTexCoord2f(left, bottom);
2783 glVertex2i(0, fbheight);
2785 /* top left */
2786 glTexCoord2f(left, top);
2787 glVertex2i(0, fbheight - drect->y2 - drect->y1);
2789 /* top right */
2790 glTexCoord2f(right, top);
2791 glVertex2i(drect->x2 - drect->x1, fbheight - drect->y2 - drect->y1);
2793 /* bottom right */
2794 glTexCoord2f(right, bottom);
2795 glVertex2i(drect->x2 - drect->x1, fbheight);
2796 glEnd();
2797 checkGLcall("glEnd and previous");
2799 /* Now read the stretched and upside down image into the destination texture */
2800 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2801 checkGLcall("glBindTexture");
2802 glCopyTexSubImage2D(This->glDescription.target,
2804 drect->x1, drect->y1, /* xoffset, yoffset */
2805 0, 0, /* We blitted the image to the origin */
2806 drect->x2 - drect->x1, drect->y2 - drect->y1);
2807 checkGLcall("glCopyTexSubImage2D");
2809 /* Write the back buffer backup back */
2810 glBindTexture(GL_TEXTURE_2D, backup ? backup : Src->glDescription.textureName);
2811 checkGLcall("glBindTexture(GL_TEXTURE_2D, Src->glDescription.textureName)");
2813 if(drawBuffer == GL_BACK) {
2814 glBegin(GL_QUADS);
2815 /* top left */
2816 glTexCoord2f(0.0, (float) fbheight / (float) Src->pow2Height);
2817 glVertex2i(0, 0);
2819 /* bottom left */
2820 glTexCoord2f(0.0, 0.0);
2821 glVertex2i(0, fbheight);
2823 /* bottom right */
2824 glTexCoord2f((float) fbwidth / (float) Src->pow2Width, 0.0);
2825 glVertex2i(fbwidth, Src->currentDesc.Height);
2827 /* top right */
2828 glTexCoord2f((float) fbwidth / (float) Src->pow2Width, (float) fbheight / (float) Src->pow2Height);
2829 glVertex2i(fbwidth, 0);
2830 glEnd();
2831 } else {
2832 /* Restore the old draw buffer */
2833 glDrawBuffer(GL_BACK);
2836 /* Cleanup */
2837 if(src != Src->glDescription.textureName && src != backup) {
2838 glDeleteTextures(1, &src);
2839 checkGLcall("glDeleteTextures(1, &src)");
2841 if(backup) {
2842 glDeleteTextures(1, &backup);
2843 checkGLcall("glDeleteTextures(1, &backup)");
2845 LEAVE_GL();
2848 /* Not called from the VTable */
2849 static HRESULT IWineD3DSurfaceImpl_BltOverride(IWineD3DSurfaceImpl *This, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
2850 WINED3DRECT rect;
2851 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2852 IWineD3DSwapChainImpl *srcSwapchain = NULL, *dstSwapchain = NULL;
2853 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2855 TRACE("(%p)->(%p,%p,%p,%08x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
2857 /* Get the swapchain. One of the surfaces has to be a primary surface */
2858 if(This->resource.pool == WINED3DPOOL_SYSTEMMEM) {
2859 WARN("Destination is in sysmem, rejecting gl blt\n");
2860 return WINED3DERR_INVALIDCALL;
2862 IWineD3DSurface_GetContainer( (IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&dstSwapchain);
2863 if(dstSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) dstSwapchain);
2864 if(Src) {
2865 if(Src->resource.pool == WINED3DPOOL_SYSTEMMEM) {
2866 WARN("Src is in sysmem, rejecting gl blt\n");
2867 return WINED3DERR_INVALIDCALL;
2869 IWineD3DSurface_GetContainer( (IWineD3DSurface *) Src, &IID_IWineD3DSwapChain, (void **)&srcSwapchain);
2870 if(srcSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) srcSwapchain);
2873 /* Early sort out of cases where no render target is used */
2874 if(!dstSwapchain && !srcSwapchain &&
2875 SrcSurface != myDevice->render_targets[0] && This != (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
2876 TRACE("No surface is render target, not using hardware blit. Src = %p, dst = %p\n", Src, This);
2877 return WINED3DERR_INVALIDCALL;
2880 /* No destination color keying supported */
2881 if(Flags & (WINEDDBLT_KEYDEST | WINEDDBLT_KEYDESTOVERRIDE)) {
2882 /* Can we support that with glBlendFunc if blitting to the frame buffer? */
2883 TRACE("Destination color key not supported in accelerated Blit, falling back to software\n");
2884 return WINED3DERR_INVALIDCALL;
2887 if (DestRect) {
2888 rect.x1 = DestRect->left;
2889 rect.y1 = DestRect->top;
2890 rect.x2 = DestRect->right;
2891 rect.y2 = DestRect->bottom;
2892 } else {
2893 rect.x1 = 0;
2894 rect.y1 = 0;
2895 rect.x2 = This->currentDesc.Width;
2896 rect.y2 = This->currentDesc.Height;
2899 /* The only case where both surfaces on a swapchain are supported is a back buffer -> front buffer blit on the same swapchain */
2900 if(dstSwapchain && dstSwapchain == srcSwapchain && dstSwapchain->backBuffer &&
2901 ((IWineD3DSurface *) This == dstSwapchain->frontBuffer) && SrcSurface == dstSwapchain->backBuffer[0]) {
2902 /* Half-life does a Blt from the back buffer to the front buffer,
2903 * Full surface size, no flags... Use present instead
2905 * This path will only be entered for d3d7 and ddraw apps, because d3d8/9 offer no way to blit TO the front buffer
2908 /* Check rects - IWineD3DDevice_Present doesn't handle them */
2909 while(1)
2911 RECT mySrcRect;
2912 TRACE("Looking if a Present can be done...\n");
2913 /* Source Rectangle must be full surface */
2914 if( SrcRect ) {
2915 if(SrcRect->left != 0 || SrcRect->top != 0 ||
2916 SrcRect->right != Src->currentDesc.Width || SrcRect->bottom != Src->currentDesc.Height) {
2917 TRACE("No, Source rectangle doesn't match\n");
2918 break;
2921 mySrcRect.left = 0;
2922 mySrcRect.top = 0;
2923 mySrcRect.right = Src->currentDesc.Width;
2924 mySrcRect.bottom = Src->currentDesc.Height;
2926 /* No stretching may occur */
2927 if(mySrcRect.right != rect.x2 - rect.x1 ||
2928 mySrcRect.bottom != rect.y2 - rect.y1) {
2929 TRACE("No, stretching is done\n");
2930 break;
2933 /* Destination must be full surface or match the clipping rectangle */
2934 if(This->clipper && ((IWineD3DClipperImpl *) This->clipper)->hWnd)
2936 RECT cliprect;
2937 POINT pos[2];
2938 GetClientRect(((IWineD3DClipperImpl *) This->clipper)->hWnd, &cliprect);
2939 pos[0].x = rect.x1;
2940 pos[0].y = rect.y1;
2941 pos[1].x = rect.x2;
2942 pos[1].y = rect.y2;
2943 MapWindowPoints(GetDesktopWindow(), ((IWineD3DClipperImpl *) This->clipper)->hWnd,
2944 pos, 2);
2946 if(pos[0].x != cliprect.left || pos[0].y != cliprect.top ||
2947 pos[1].x != cliprect.right || pos[1].y != cliprect.bottom)
2949 TRACE("No, dest rectangle doesn't match(clipper)\n");
2950 TRACE("Clip rect at (%d,%d)-(%d,%d)\n", cliprect.left, cliprect.top, cliprect.right, cliprect.bottom);
2951 TRACE("Blt dest: (%d,%d)-(%d,%d)\n", rect.x1, rect.y1, rect.x2, rect.y2);
2952 break;
2955 else
2957 if(rect.x1 != 0 || rect.y1 != 0 ||
2958 rect.x2 != This->currentDesc.Width || rect.y2 != This->currentDesc.Height) {
2959 TRACE("No, dest rectangle doesn't match(surface size)\n");
2960 break;
2964 TRACE("Yes\n");
2966 /* These flags are unimportant for the flag check, remove them */
2967 if((Flags & ~(WINEDDBLT_DONOTWAIT | WINEDDBLT_WAIT)) == 0) {
2968 WINED3DSWAPEFFECT orig_swap = dstSwapchain->presentParms.SwapEffect;
2970 /* The idea behind this is that a glReadPixels and a glDrawPixels call
2971 * take very long, while a flip is fast.
2972 * This applies to Half-Life, which does such Blts every time it finished
2973 * a frame, and to Prince of Persia 3D, which uses this to draw at least the main
2974 * menu. This is also used by all apps when they do windowed rendering
2976 * The problem is that flipping is not really the same as copying. After a
2977 * Blt the front buffer is a copy of the back buffer, and the back buffer is
2978 * untouched. Therefore it's necessary to override the swap effect
2979 * and to set it back after the flip.
2981 * Windowed Direct3D < 7 apps do the same. The D3D7 sdk demos are nice
2982 * testcases.
2985 dstSwapchain->presentParms.SwapEffect = WINED3DSWAPEFFECT_COPY;
2986 dstSwapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
2988 TRACE("Full screen back buffer -> front buffer blt, performing a flip instead\n");
2989 IWineD3DSwapChain_Present((IWineD3DSwapChain *) dstSwapchain, NULL, NULL, 0, NULL, 0);
2991 dstSwapchain->presentParms.SwapEffect = orig_swap;
2993 return WINED3D_OK;
2995 break;
2998 TRACE("Unsupported blit between buffers on the same swapchain\n");
2999 return WINED3DERR_INVALIDCALL;
3000 } else if((dstSwapchain || This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) &&
3001 (srcSwapchain || SrcSurface == myDevice->render_targets[0]) ) {
3002 ERR("Can't perform hardware blit between 2 different swapchains, falling back to software\n");
3003 return WINED3DERR_INVALIDCALL;
3006 if(srcSwapchain || SrcSurface == myDevice->render_targets[0]) {
3007 /* Blit from render target to texture */
3008 WINED3DRECT srect;
3009 BOOL upsideDown, stretchx;
3011 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3012 TRACE("Color keying not supported by frame buffer to texture blit\n");
3013 return WINED3DERR_INVALIDCALL;
3014 /* Destination color key is checked above */
3017 /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
3018 * glCopyTexSubImage is a bit picky about the parameters we pass to it
3020 if(SrcRect) {
3021 if(SrcRect->top < SrcRect->bottom) {
3022 srect.y1 = SrcRect->top;
3023 srect.y2 = SrcRect->bottom;
3024 upsideDown = FALSE;
3025 } else {
3026 srect.y1 = SrcRect->bottom;
3027 srect.y2 = SrcRect->top;
3028 upsideDown = TRUE;
3030 srect.x1 = SrcRect->left;
3031 srect.x2 = SrcRect->right;
3032 } else {
3033 srect.x1 = 0;
3034 srect.y1 = 0;
3035 srect.x2 = Src->currentDesc.Width;
3036 srect.y2 = Src->currentDesc.Height;
3037 upsideDown = FALSE;
3039 if(rect.x1 > rect.x2) {
3040 UINT tmp = rect.x2;
3041 rect.x2 = rect.x1;
3042 rect.x1 = tmp;
3043 upsideDown = !upsideDown;
3045 if(!srcSwapchain) {
3046 TRACE("Reading from an offscreen target\n");
3047 upsideDown = !upsideDown;
3050 if(rect.x2 - rect.x1 != srect.x2 - srect.x1) {
3051 stretchx = TRUE;
3052 } else {
3053 stretchx = FALSE;
3056 /* Blt is a pretty powerful call, while glCopyTexSubImage2D is not. glCopyTexSubImage cannot
3057 * flip the image nor scale it.
3059 * -> If the app asks for a unscaled, upside down copy, just perform one glCopyTexSubImage2D call
3060 * -> If the app wants a image width an unscaled width, copy it line per line
3061 * -> If the app wants a image that is scaled on the x axis, and the destination rectangle is smaller
3062 * than the frame buffer, draw an upside down scaled image onto the fb, read it back and restore the
3063 * back buffer. This is slower than reading line per line, thus not used for flipping
3064 * -> If the app wants a scaled image with a dest rect that is bigger than the fb, it has to be copied
3065 * pixel by pixel
3067 * If EXT_framebuffer_blit is supported that can be used instead. Note that EXT_framebuffer_blit implies
3068 * FBO support, so it doesn't really make sense to try and make it work with different offscreen rendering
3069 * backends.
3071 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && GL_SUPPORT(EXT_FRAMEBUFFER_BLIT)) {
3072 stretch_rect_fbo((IWineD3DDevice *)myDevice, SrcSurface, &srect,
3073 (IWineD3DSurface *)This, &rect, Filter, upsideDown);
3074 } else if((!stretchx) || rect.x2 - rect.x1 > Src->currentDesc.Width ||
3075 rect.y2 - rect.y1 > Src->currentDesc.Height) {
3076 TRACE("No stretching in x direction, using direct framebuffer -> texture copy\n");
3077 fb_copy_to_texture_direct(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
3078 } else {
3079 TRACE("Using hardware stretching to flip / stretch the texture\n");
3080 fb_copy_to_texture_hwstretch(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
3083 if(!(This->Flags & SFLAG_DONOTFREE)) {
3084 HeapFree(GetProcessHeap(), 0, This->resource.allocatedMemory);
3085 This->resource.allocatedMemory = NULL;
3086 } else {
3087 This->Flags &= ~SFLAG_INSYSMEM;
3089 /* The texture is now most up to date - If the surface is a render target and has a drawable, this
3090 * path is never entered
3092 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) This, SFLAG_INTEXTURE, TRUE);
3094 return WINED3D_OK;
3095 } else if(Src) {
3096 /* Blit from offscreen surface to render target */
3097 float glTexCoord[4];
3098 DWORD oldCKeyFlags = Src->CKeyFlags;
3099 WINEDDCOLORKEY oldBltCKey = This->SrcBltCKey;
3100 RECT SourceRectangle;
3102 TRACE("Blt from surface %p to rendertarget %p\n", Src, This);
3104 if(SrcRect) {
3105 SourceRectangle.left = SrcRect->left;
3106 SourceRectangle.right = SrcRect->right;
3107 SourceRectangle.top = SrcRect->top;
3108 SourceRectangle.bottom = SrcRect->bottom;
3109 } else {
3110 SourceRectangle.left = 0;
3111 SourceRectangle.right = Src->currentDesc.Width;
3112 SourceRectangle.top = 0;
3113 SourceRectangle.bottom = Src->currentDesc.Height;
3116 if(!CalculateTexRect(Src, &SourceRectangle, glTexCoord)) {
3117 /* Fall back to software */
3118 WARN("(%p) Source texture area (%d,%d)-(%d,%d) is too big\n", Src,
3119 SourceRectangle.left, SourceRectangle.top,
3120 SourceRectangle.right, SourceRectangle.bottom);
3121 return WINED3DERR_INVALIDCALL;
3124 /* Color keying: Check if we have to do a color keyed blt,
3125 * and if not check if a color key is activated.
3127 * Just modify the color keying parameters in the surface and restore them afterwards
3128 * The surface keeps track of the color key last used to load the opengl surface.
3129 * PreLoad will catch the change to the flags and color key and reload if necessary.
3131 if(Flags & WINEDDBLT_KEYSRC) {
3132 /* Use color key from surface */
3133 } else if(Flags & WINEDDBLT_KEYSRCOVERRIDE) {
3134 /* Use color key from DDBltFx */
3135 Src->CKeyFlags |= WINEDDSD_CKSRCBLT;
3136 This->SrcBltCKey = DDBltFx->ddckSrcColorkey;
3137 } else {
3138 /* Do not use color key */
3139 Src->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
3142 /* Now load the surface */
3143 IWineD3DSurface_PreLoad((IWineD3DSurface *) Src);
3146 /* Activate the destination context, set it up for blitting */
3147 ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
3148 ENTER_GL();
3150 if(!dstSwapchain) {
3151 TRACE("Drawing to offscreen buffer\n");
3152 glDrawBuffer(myDevice->offscreenBuffer);
3153 checkGLcall("glDrawBuffer");
3154 } else {
3155 GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *)This, (IWineD3DSwapChain *)dstSwapchain);
3156 TRACE("Drawing to %#x buffer\n", buffer);
3157 glDrawBuffer(buffer);
3158 checkGLcall("glDrawBuffer");
3161 /* Bind the texture */
3162 glBindTexture(GL_TEXTURE_2D, Src->glDescription.textureName);
3163 checkGLcall("glBindTexture");
3165 /* Filtering for StretchRect */
3166 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
3167 stateLookup[WINELOOKUP_MAGFILTER][Filter - minLookup[WINELOOKUP_MAGFILTER]]);
3168 checkGLcall("glTexParameteri");
3169 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
3170 minMipLookup[Filter][WINED3DTEXF_NONE]);
3171 checkGLcall("glTexParameteri");
3172 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
3173 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
3174 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
3175 checkGLcall("glTexEnvi");
3177 /* This is for color keying */
3178 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3179 glEnable(GL_ALPHA_TEST);
3180 checkGLcall("glEnable GL_ALPHA_TEST");
3181 glAlphaFunc(GL_NOTEQUAL, 0.0);
3182 checkGLcall("glAlphaFunc\n");
3183 } else {
3184 glDisable(GL_ALPHA_TEST);
3185 checkGLcall("glDisable GL_ALPHA_TEST");
3188 /* Draw a textured quad
3190 glBegin(GL_QUADS);
3192 glColor3d(1.0f, 1.0f, 1.0f);
3193 glTexCoord2f(glTexCoord[0], glTexCoord[2]);
3194 glVertex3f(rect.x1,
3195 rect.y1,
3196 0.0);
3198 glTexCoord2f(glTexCoord[0], glTexCoord[3]);
3199 glVertex3f(rect.x1, rect.y2, 0.0);
3201 glTexCoord2f(glTexCoord[1], glTexCoord[3]);
3202 glVertex3f(rect.x2,
3203 rect.y2,
3204 0.0);
3206 glTexCoord2f(glTexCoord[1], glTexCoord[2]);
3207 glVertex3f(rect.x2,
3208 rect.y1,
3209 0.0);
3210 glEnd();
3211 checkGLcall("glEnd");
3213 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3214 glDisable(GL_ALPHA_TEST);
3215 checkGLcall("glDisable(GL_ALPHA_TEST)");
3218 /* Unbind the texture */
3219 glBindTexture(GL_TEXTURE_2D, 0);
3220 checkGLcall("glEnable glBindTexture");
3222 /* The draw buffer should only need to be restored if we were drawing to the front buffer, and there is a back buffer.
3223 * otherwise the context manager should choose between GL_BACK / offscreenDrawBuffer
3225 if(dstSwapchain && This == (IWineD3DSurfaceImpl *) dstSwapchain->frontBuffer && dstSwapchain->backBuffer) {
3226 glDrawBuffer(GL_BACK);
3227 checkGLcall("glDrawBuffer");
3229 /* Restore the color key parameters */
3230 Src->CKeyFlags = oldCKeyFlags;
3231 This->SrcBltCKey = oldBltCKey;
3233 LEAVE_GL();
3235 /* TODO: If the surface is locked often, perform the Blt in software on the memory instead */
3236 /* The surface is now in the drawable. On onscreen surfaces or without fbos the texture
3237 * is outdated now
3239 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) This, SFLAG_INDRAWABLE, TRUE);
3240 /* TODO: This should be moved to ModifyLocation() */
3241 if(!(dstSwapchain || wined3d_settings.offscreen_rendering_mode != ORM_FBO)) {
3242 This->Flags |= SFLAG_INTEXTURE;
3245 return WINED3D_OK;
3246 } else {
3247 /* Source-Less Blit to render target */
3248 if (Flags & WINEDDBLT_COLORFILL) {
3249 /* This is easy to handle for the D3D Device... */
3250 DWORD color;
3252 TRACE("Colorfill\n");
3254 /* The color as given in the Blt function is in the format of the frame-buffer...
3255 * 'clear' expect it in ARGB format => we need to do some conversion :-)
3257 if (This->resource.format == WINED3DFMT_P8) {
3258 if (This->palette) {
3259 color = ((0xFF000000) |
3260 (This->palette->palents[DDBltFx->u5.dwFillColor].peRed << 16) |
3261 (This->palette->palents[DDBltFx->u5.dwFillColor].peGreen << 8) |
3262 (This->palette->palents[DDBltFx->u5.dwFillColor].peBlue));
3263 } else {
3264 color = 0xFF000000;
3267 else if (This->resource.format == WINED3DFMT_R5G6B5) {
3268 if (DDBltFx->u5.dwFillColor == 0xFFFF) {
3269 color = 0xFFFFFFFF;
3270 } else {
3271 color = ((0xFF000000) |
3272 ((DDBltFx->u5.dwFillColor & 0xF800) << 8) |
3273 ((DDBltFx->u5.dwFillColor & 0x07E0) << 5) |
3274 ((DDBltFx->u5.dwFillColor & 0x001F) << 3));
3277 else if ((This->resource.format == WINED3DFMT_R8G8B8) ||
3278 (This->resource.format == WINED3DFMT_X8R8G8B8) ) {
3279 color = 0xFF000000 | DDBltFx->u5.dwFillColor;
3281 else if (This->resource.format == WINED3DFMT_A8R8G8B8) {
3282 color = DDBltFx->u5.dwFillColor;
3284 else {
3285 ERR("Wrong surface type for BLT override(Format doesn't match) !\n");
3286 return WINED3DERR_INVALIDCALL;
3289 TRACE("Calling GetSwapChain with mydevice = %p\n", myDevice);
3290 if(dstSwapchain && dstSwapchain->backBuffer && This == (IWineD3DSurfaceImpl*) dstSwapchain->backBuffer[0]) {
3291 glDrawBuffer(GL_BACK);
3292 checkGLcall("glDrawBuffer(GL_BACK)");
3293 } else if (dstSwapchain && This == (IWineD3DSurfaceImpl*) dstSwapchain->frontBuffer) {
3294 glDrawBuffer(GL_FRONT);
3295 checkGLcall("glDrawBuffer(GL_FRONT)");
3296 } else if(This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
3297 glDrawBuffer(myDevice->offscreenBuffer);
3298 checkGLcall("glDrawBuffer(myDevice->offscreenBuffer3)");
3299 } else {
3300 TRACE("Surface is higher back buffer, falling back to software\n");
3301 return WINED3DERR_INVALIDCALL;
3304 TRACE("(%p) executing Render Target override, color = %x\n", This, color);
3306 IWineD3DDevice_Clear( (IWineD3DDevice *) myDevice,
3307 1 /* Number of rectangles */,
3308 &rect,
3309 WINED3DCLEAR_TARGET,
3310 color,
3311 0.0 /* Z */,
3312 0 /* Stencil */);
3314 /* Restore the original draw buffer */
3315 if(!dstSwapchain) {
3316 glDrawBuffer(myDevice->offscreenBuffer);
3317 } else if(dstSwapchain->backBuffer && dstSwapchain->backBuffer[0]) {
3318 glDrawBuffer(GL_BACK);
3320 vcheckGLcall("glDrawBuffer");
3322 return WINED3D_OK;
3326 /* Default: Fall back to the generic blt. Not an error, a TRACE is enough */
3327 TRACE("Didn't find any usable render target setup for hw blit, falling back to software\n");
3328 return WINED3DERR_INVALIDCALL;
3331 static HRESULT WINAPI IWineD3DSurfaceImpl_BltZ(IWineD3DSurfaceImpl *This, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx)
3333 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3334 float depth;
3336 if (Flags & WINEDDBLT_DEPTHFILL) {
3337 switch(This->resource.format) {
3338 case WINED3DFMT_D16:
3339 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000ffff;
3340 break;
3341 case WINED3DFMT_D15S1:
3342 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000fffe;
3343 break;
3344 case WINED3DFMT_D24S8:
3345 case WINED3DFMT_D24X8:
3346 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00ffffff;
3347 break;
3348 case WINED3DFMT_D32:
3349 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0xffffffff;
3350 break;
3351 default:
3352 depth = 0.0;
3353 ERR("Unexpected format for depth fill: %s\n", debug_d3dformat(This->resource.format));
3356 return IWineD3DDevice_Clear((IWineD3DDevice *) myDevice,
3357 DestRect == NULL ? 0 : 1,
3358 (WINED3DRECT *) DestRect,
3359 WINED3DCLEAR_ZBUFFER,
3360 0x00000000,
3361 depth,
3362 0x00000000);
3365 FIXME("(%p): Unsupp depthstencil blit\n", This);
3366 return WINED3DERR_INVALIDCALL;
3369 static HRESULT WINAPI IWineD3DSurfaceImpl_Blt(IWineD3DSurface *iface, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
3370 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3371 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
3372 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3373 TRACE("(%p)->(%p,%p,%p,%x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3374 TRACE("(%p): Usage is %s\n", This, debug_d3dusage(This->resource.usage));
3376 /* Accessing the depth stencil is supposed to fail between a BeginScene and EndScene pair,
3377 * except depth blits, which seem to work
3379 if(iface == myDevice->stencilBufferTarget || (SrcSurface && SrcSurface == myDevice->stencilBufferTarget)) {
3380 if(myDevice->inScene && !(Flags & WINEDDBLT_DEPTHFILL)) {
3381 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3382 return WINED3DERR_INVALIDCALL;
3383 } else if(IWineD3DSurfaceImpl_BltZ(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx) == WINED3D_OK) {
3384 TRACE("Z Blit override handled the blit\n");
3385 return WINED3D_OK;
3389 /* Special cases for RenderTargets */
3390 if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3391 ( Src && (Src->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3392 if(IWineD3DSurfaceImpl_BltOverride(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter) == WINED3D_OK) return WINED3D_OK;
3395 /* For the rest call the X11 surface implementation.
3396 * For RenderTargets this should be implemented OpenGL accelerated in BltOverride,
3397 * other Blts are rather rare
3399 return IWineD3DBaseSurfaceImpl_Blt(iface, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter);
3402 HRESULT WINAPI IWineD3DSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty, IWineD3DSurface *Source, RECT *rsrc, DWORD trans) {
3403 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3404 IWineD3DSurfaceImpl *srcImpl = (IWineD3DSurfaceImpl *) Source;
3405 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3406 TRACE("(%p)->(%d, %d, %p, %p, %08x\n", iface, dstx, dsty, Source, rsrc, trans);
3408 if(myDevice->inScene &&
3409 (iface == myDevice->stencilBufferTarget ||
3410 (Source && Source == myDevice->stencilBufferTarget))) {
3411 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3412 return WINED3DERR_INVALIDCALL;
3415 /* Special cases for RenderTargets */
3416 if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3417 ( srcImpl && (srcImpl->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3419 RECT SrcRect, DstRect;
3420 DWORD Flags=0;
3422 if(rsrc) {
3423 SrcRect.left = rsrc->left;
3424 SrcRect.top= rsrc->top;
3425 SrcRect.bottom = rsrc->bottom;
3426 SrcRect.right = rsrc->right;
3427 } else {
3428 SrcRect.left = 0;
3429 SrcRect.top = 0;
3430 SrcRect.right = srcImpl->currentDesc.Width;
3431 SrcRect.bottom = srcImpl->currentDesc.Height;
3434 DstRect.left = dstx;
3435 DstRect.top=dsty;
3436 DstRect.right = dstx + SrcRect.right - SrcRect.left;
3437 DstRect.bottom = dsty + SrcRect.bottom - SrcRect.top;
3439 /* Convert BltFast flags into Btl ones because it is called from SurfaceImpl_Blt as well */
3440 if(trans & WINEDDBLTFAST_SRCCOLORKEY)
3441 Flags |= WINEDDBLT_KEYSRC;
3442 if(trans & WINEDDBLTFAST_DESTCOLORKEY)
3443 Flags |= WINEDDBLT_KEYDEST;
3444 if(trans & WINEDDBLTFAST_WAIT)
3445 Flags |= WINEDDBLT_WAIT;
3446 if(trans & WINEDDBLTFAST_DONOTWAIT)
3447 Flags |= WINEDDBLT_DONOTWAIT;
3449 if(IWineD3DSurfaceImpl_BltOverride(This, &DstRect, Source, &SrcRect, Flags, NULL, WINED3DTEXF_POINT) == WINED3D_OK) return WINED3D_OK;
3453 return IWineD3DBaseSurfaceImpl_BltFast(iface, dstx, dsty, Source, rsrc, trans);
3456 static HRESULT WINAPI IWineD3DSurfaceImpl_PrivateSetup(IWineD3DSurface *iface) {
3457 /** Check against the maximum texture sizes supported by the video card **/
3458 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3459 unsigned int pow2Width, pow2Height;
3460 const GlPixelFormatDesc *glDesc;
3462 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
3463 /* Setup some glformat defaults */
3464 This->glDescription.glFormat = glDesc->glFormat;
3465 This->glDescription.glFormatInternal = glDesc->glInternal;
3466 This->glDescription.glType = glDesc->glType;
3468 This->glDescription.textureName = 0;
3469 This->glDescription.target = GL_TEXTURE_2D;
3471 /* Non-power2 support */
3472 if (GL_SUPPORT(ARB_TEXTURE_NON_POWER_OF_TWO)) {
3473 pow2Width = This->currentDesc.Width;
3474 pow2Height = This->currentDesc.Height;
3475 } else {
3476 /* Find the nearest pow2 match */
3477 pow2Width = pow2Height = 1;
3478 while (pow2Width < This->currentDesc.Width) pow2Width <<= 1;
3479 while (pow2Height < This->currentDesc.Height) pow2Height <<= 1;
3481 This->pow2Width = pow2Width;
3482 This->pow2Height = pow2Height;
3484 if (pow2Width > This->currentDesc.Width || pow2Height > This->currentDesc.Height) {
3485 WINED3DFORMAT Format = This->resource.format;
3486 /** TODO: add support for non power two compressed textures **/
3487 if (Format == WINED3DFMT_DXT1 || Format == WINED3DFMT_DXT2 || Format == WINED3DFMT_DXT3
3488 || Format == WINED3DFMT_DXT4 || Format == WINED3DFMT_DXT5) {
3489 FIXME("(%p) Compressed non-power-two textures are not supported w(%d) h(%d)\n",
3490 This, This->currentDesc.Width, This->currentDesc.Height);
3491 return WINED3DERR_NOTAVAILABLE;
3495 if(pow2Width != This->currentDesc.Width ||
3496 pow2Height != This->currentDesc.Height) {
3497 This->Flags |= SFLAG_NONPOW2;
3500 TRACE("%p\n", This);
3501 if ((This->pow2Width > GL_LIMITS(texture_size) || This->pow2Height > GL_LIMITS(texture_size)) && !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL))) {
3502 /* one of three options
3503 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)
3504 2: Set the texture to the maximum size (bad idea)
3505 3: WARN and return WINED3DERR_NOTAVAILABLE;
3506 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.
3508 WARN("(%p) Creating an oversized surface\n", This);
3509 This->Flags |= SFLAG_OVERSIZE;
3511 /* This will be initialized on the first blt */
3512 This->glRect.left = 0;
3513 This->glRect.top = 0;
3514 This->glRect.right = 0;
3515 This->glRect.bottom = 0;
3516 } else {
3517 /* No oversize, gl rect is the full texture size */
3518 This->Flags &= ~SFLAG_OVERSIZE;
3519 This->glRect.left = 0;
3520 This->glRect.top = 0;
3521 This->glRect.right = This->pow2Width;
3522 This->glRect.bottom = This->pow2Height;
3525 if(This->resource.allocatedMemory == NULL) {
3526 /* Make sure memory exists from the start, and it is initialized properly. D3D initializes surfaces,
3527 * gl does not, so we need to upload zeroes to init the gl texture.
3529 This->resource.allocatedMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, This->resource.size + 4);
3531 This->Flags |= SFLAG_INSYSMEM;
3533 return WINED3D_OK;
3536 static void WINAPI IWineD3DSurfaceImpl_ModifyLocation(IWineD3DSurface *iface, DWORD flag, BOOL persistent) {
3537 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3539 TRACE("(%p)->(%s, %s)\n", iface,
3540 flag == SFLAG_INSYSMEM ? "SFLAG_INSYSMEM" : flag == SFLAG_INDRAWABLE ? "SFLAG_INDRAWABLE" : "SFLAG_INTEXTURE",
3541 persistent ? "TRUE" : "FALSE");
3543 /* TODO: For offscreen textures with fbo offscreen rendering the drawable is the same as the texture.*/
3544 if(persistent) {
3545 This->Flags &= ~SFLAG_LOCATIONS;
3546 This->Flags |= flag;
3547 } else {
3548 This->Flags &= ~flag;
3552 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadLocation(IWineD3DSurface *iface, DWORD flag, const RECT *rect) {
3553 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3554 TRACE("(%p)->(%s, %p)\n", iface,
3555 flag == SFLAG_INSYSMEM ? "SFLAG_INSYSMEM" : flag == SFLAG_INDRAWABLE ? "SFLAG_INDRAWABLE" : "SFLAG_INTEXTURE",
3556 rect);
3557 if(rect) {
3558 TRACE("Rectangle: (%d,%d)-(%d,%d)\n", rect->left, rect->top, rect->right, rect->bottom);
3561 /* TODO: For fbo targets, texture == drawable */
3562 if(This->Flags & flag) {
3563 TRACE("Location already up to date\n");
3564 return WINED3D_OK;
3567 if(!(This->Flags & SFLAG_LOCATIONS)) {
3568 ERR("Surface does not have any up to date location\n");
3569 This->Flags |= SFLAG_LOST;
3570 return WINED3DERR_DEVICELOST;
3573 if(flag == SFLAG_INSYSMEM) {
3574 /* Download the surface to system memory */
3575 if(This->Flags & SFLAG_INTEXTURE) {
3576 /* Download texture to sysmem */
3577 } else {
3578 /* Download drawable to sysmem */
3580 } else if(flag == SFLAG_INDRAWABLE) {
3581 if(This->Flags & SFLAG_INTEXTURE) {
3582 /* Blit texture to drawable */
3583 } else {
3584 /* Load drawable from sysmem */
3586 } else /* if(flag == SFLAG_INTEXTURE) */ {
3587 if(This->Flags & SFLAG_INDRAWABLE) {
3588 /* glCopyTexImage the drawable into the texture */
3589 } else {
3590 /* Load the texture from sysmem */
3594 return WINED3D_OK;
3597 const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl =
3599 /* IUnknown */
3600 IWineD3DBaseSurfaceImpl_QueryInterface,
3601 IWineD3DBaseSurfaceImpl_AddRef,
3602 IWineD3DSurfaceImpl_Release,
3603 /* IWineD3DResource */
3604 IWineD3DBaseSurfaceImpl_GetParent,
3605 IWineD3DBaseSurfaceImpl_GetDevice,
3606 IWineD3DBaseSurfaceImpl_SetPrivateData,
3607 IWineD3DBaseSurfaceImpl_GetPrivateData,
3608 IWineD3DBaseSurfaceImpl_FreePrivateData,
3609 IWineD3DBaseSurfaceImpl_SetPriority,
3610 IWineD3DBaseSurfaceImpl_GetPriority,
3611 IWineD3DSurfaceImpl_PreLoad,
3612 IWineD3DBaseSurfaceImpl_GetType,
3613 /* IWineD3DSurface */
3614 IWineD3DBaseSurfaceImpl_GetContainer,
3615 IWineD3DBaseSurfaceImpl_GetDesc,
3616 IWineD3DSurfaceImpl_LockRect,
3617 IWineD3DSurfaceImpl_UnlockRect,
3618 IWineD3DSurfaceImpl_GetDC,
3619 IWineD3DSurfaceImpl_ReleaseDC,
3620 IWineD3DSurfaceImpl_Flip,
3621 IWineD3DSurfaceImpl_Blt,
3622 IWineD3DBaseSurfaceImpl_GetBltStatus,
3623 IWineD3DBaseSurfaceImpl_GetFlipStatus,
3624 IWineD3DBaseSurfaceImpl_IsLost,
3625 IWineD3DBaseSurfaceImpl_Restore,
3626 IWineD3DSurfaceImpl_BltFast,
3627 IWineD3DBaseSurfaceImpl_GetPalette,
3628 IWineD3DBaseSurfaceImpl_SetPalette,
3629 IWineD3DBaseSurfaceImpl_RealizePalette,
3630 IWineD3DBaseSurfaceImpl_SetColorKey,
3631 IWineD3DBaseSurfaceImpl_GetPitch,
3632 IWineD3DSurfaceImpl_SetMem,
3633 IWineD3DBaseSurfaceImpl_SetOverlayPosition,
3634 IWineD3DBaseSurfaceImpl_GetOverlayPosition,
3635 IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder,
3636 IWineD3DBaseSurfaceImpl_UpdateOverlay,
3637 IWineD3DBaseSurfaceImpl_SetClipper,
3638 IWineD3DBaseSurfaceImpl_GetClipper,
3639 /* Internal use: */
3640 IWineD3DSurfaceImpl_AddDirtyRect,
3641 IWineD3DSurfaceImpl_LoadTexture,
3642 IWineD3DSurfaceImpl_SaveSnapshot,
3643 IWineD3DBaseSurfaceImpl_SetContainer,
3644 IWineD3DSurfaceImpl_SetGlTextureDesc,
3645 IWineD3DSurfaceImpl_GetGlDesc,
3646 IWineD3DSurfaceImpl_GetData,
3647 IWineD3DSurfaceImpl_SetFormat,
3648 IWineD3DSurfaceImpl_PrivateSetup,
3649 IWineD3DSurfaceImpl_ModifyLocation,
3650 IWineD3DSurfaceImpl_LoadLocation