wined3d: Call ActivateContext regardless of WINED3DCREATE_MULTITHREADED.
[wine/hacks.git] / dlls / wined3d / surface.c
blob29bc21c50c94d3fad1f20726a0483b20357bdb91
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-2007 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 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
42 if (0 == This->glDescription.textureName) {
43 ERR("Surface does not have a texture, but SFLAG_INTEXTURE is set\n");
44 return;
47 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
49 if(This->Flags & SFLAG_CONVERTED) {
50 FIXME("Read back converted textures unsupported, format=%s\n", debug_d3dformat(This->resource.format));
51 return;
54 ENTER_GL();
55 /* Make sure that a proper texture unit is selected, bind the texture
56 * and dirtify the sampler to restore the texture on the next draw
58 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
59 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
60 checkGLcall("glActiveTextureARB");
62 IWineD3DDeviceImpl_MarkStateDirty(This->resource.wineD3DDevice, STATE_SAMPLER(0));
63 IWineD3DSurface_BindTexture((IWineD3DSurface *) This);
65 if (This->resource.format == WINED3DFMT_DXT1 ||
66 This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
67 This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) {
68 if (!GL_SUPPORT(EXT_TEXTURE_COMPRESSION_S3TC)) { /* We can assume this as the texture would not have been created otherwise */
69 FIXME("(%p) : Attempting to lock a compressed texture when texture compression isn't supported by opengl\n", This);
70 } else {
71 TRACE("(%p) : Calling glGetCompressedTexImageARB level %d, format %#x, type %#x, data %p\n", This, This->glDescription.level,
72 This->glDescription.glFormat, This->glDescription.glType, This->resource.allocatedMemory);
74 if(This->Flags & SFLAG_PBO) {
75 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
76 checkGLcall("glBindBufferARB");
77 GL_EXTCALL(glGetCompressedTexImageARB(This->glDescription.target, This->glDescription.level, NULL));
78 checkGLcall("glGetCompressedTexImageARB()");
79 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
80 checkGLcall("glBindBufferARB");
81 } else {
82 GL_EXTCALL(glGetCompressedTexImageARB(This->glDescription.target, This->glDescription.level, This->resource.allocatedMemory));
83 checkGLcall("glGetCompressedTexImageARB()");
86 LEAVE_GL();
87 } else {
88 void *mem;
89 int src_pitch = 0;
90 int dst_pitch = 0;
92 if (This->Flags & SFLAG_NONPOW2) {
93 unsigned char alignment = This->resource.wineD3DDevice->surface_alignment;
94 src_pitch = This->bytesPerPixel * This->pow2Width;
95 dst_pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);
96 src_pitch = (src_pitch + alignment - 1) & ~(alignment - 1);
97 mem = HeapAlloc(GetProcessHeap(), 0, src_pitch * This->pow2Height);
98 } else {
99 mem = This->resource.allocatedMemory;
102 TRACE("(%p) : Calling glGetTexImage level %d, format %#x, type %#x, data %p\n", This, This->glDescription.level,
103 This->glDescription.glFormat, This->glDescription.glType, mem);
105 if(This->Flags & SFLAG_PBO) {
106 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
107 checkGLcall("glBindBufferARB");
109 glGetTexImage(This->glDescription.target, This->glDescription.level, This->glDescription.glFormat,
110 This->glDescription.glType, NULL);
111 checkGLcall("glGetTexImage()");
113 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
114 checkGLcall("glBindBufferARB");
115 } else {
116 glGetTexImage(This->glDescription.target, This->glDescription.level, This->glDescription.glFormat,
117 This->glDescription.glType, mem);
118 checkGLcall("glGetTexImage()");
120 LEAVE_GL();
122 if (This->Flags & SFLAG_NONPOW2) {
123 LPBYTE src_data, dst_data;
124 int y;
126 * Some games (e.g. warhammer 40k) don't work properly with the odd pitches, preventing
127 * the surface pitch from being used to box non-power2 textures. Instead we have to use a hack to
128 * repack the texture so that the bpp * width pitch can be used instead of bpp * pow2width.
130 * We're doing this...
132 * instead of boxing the texture :
133 * |<-texture width ->| -->pow2width| /\
134 * |111111111111111111| | |
135 * |222 Texture 222222| boxed empty | texture height
136 * |3333 Data 33333333| | |
137 * |444444444444444444| | \/
138 * ----------------------------------- |
139 * | boxed empty | boxed empty | pow2height
140 * | | | \/
141 * -----------------------------------
144 * we're repacking the data to the expected texture width
146 * |<-texture width ->| -->pow2width| /\
147 * |111111111111111111222222222222222| |
148 * |222333333333333333333444444444444| texture height
149 * |444444 | |
150 * | | \/
151 * | | |
152 * | empty | pow2height
153 * | | \/
154 * -----------------------------------
156 * == is the same as
158 * |<-texture width ->| /\
159 * |111111111111111111|
160 * |222222222222222222|texture height
161 * |333333333333333333|
162 * |444444444444444444| \/
163 * --------------------
165 * this also means that any references to allocatedMemory should work with the data as if were a
166 * standard texture with a non-power2 width instead of texture boxed up to be a power2 texture.
168 * internally the texture is still stored in a boxed format so any references to textureName will
169 * get a boxed texture with width pow2width and not a texture of width currentDesc.Width.
171 * Performance should not be an issue, because applications normally do not lock the surfaces when
172 * rendering. If an app does, the SFLAG_DYNLOCK flag will kick in and the memory copy won't be released,
173 * and doesn't have to be re-read.
175 src_data = mem;
176 dst_data = This->resource.allocatedMemory;
177 TRACE("(%p) : Repacking the surface data from pitch %d to pitch %d\n", This, src_pitch, dst_pitch);
178 for (y = 1 ; y < This->currentDesc.Height; y++) {
179 /* skip the first row */
180 src_data += src_pitch;
181 dst_data += dst_pitch;
182 memcpy(dst_data, src_data, dst_pitch);
185 HeapFree(GetProcessHeap(), 0, mem);
189 /* Surface has now been downloaded */
190 This->Flags |= SFLAG_INSYSMEM;
193 static void surface_upload_data(IWineD3DSurfaceImpl *This, GLenum internal, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *data) {
194 if (This->resource.format == WINED3DFMT_DXT1 ||
195 This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
196 This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) {
197 if (!GL_SUPPORT(EXT_TEXTURE_COMPRESSION_S3TC)) {
198 FIXME("Using DXT1/3/5 without advertized support\n");
199 } else {
200 /* glCompressedTexSubImage2D for uploading and glTexImage2D for allocating does not work well on some drivers(r200 dri, MacOS ATI driver)
201 * glCompressedTexImage2D does not accept NULL pointers. So for compressed textures surface_allocate_surface does nothing, and this
202 * function uses glCompressedTexImage2D instead of the SubImage call
204 TRACE("(%p) : Calling glCompressedTexSubImage2D w %d, h %d, data %p\n", This, width, height, data);
205 ENTER_GL();
207 if(This->Flags & SFLAG_PBO) {
208 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
209 checkGLcall("glBindBufferARB");
210 TRACE("(%p) pbo: %#x, data: %p\n", This, This->pbo, data);
212 GL_EXTCALL(glCompressedTexImage2DARB(This->glDescription.target, This->glDescription.level, internal,
213 width, height, 0 /* border */, This->resource.size, NULL));
214 checkGLcall("glCompressedTexSubImage2D");
216 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
217 checkGLcall("glBindBufferARB");
218 } else {
219 GL_EXTCALL(glCompressedTexImage2DARB(This->glDescription.target, This->glDescription.level, internal,
220 width, height, 0 /* border */, This->resource.size, data));
221 checkGLcall("glCompressedTexSubImage2D");
223 LEAVE_GL();
225 } else {
226 TRACE("(%p) : Calling glTexSubImage2D w %d, h %d, data, %p\n", This, width, height, data);
227 ENTER_GL();
229 if(This->Flags & SFLAG_PBO) {
230 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
231 checkGLcall("glBindBufferARB");
232 TRACE("(%p) pbo: %#x, data: %p\n", This, This->pbo, data);
234 glTexSubImage2D(This->glDescription.target, This->glDescription.level, 0, 0, width, height, format, type, NULL);
235 checkGLcall("glTexSubImage2D");
237 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
238 checkGLcall("glBindBufferARB");
240 else {
241 glTexSubImage2D(This->glDescription.target, This->glDescription.level, 0, 0, width, height, format, type, data);
242 checkGLcall("glTexSubImage2D");
245 LEAVE_GL();
249 static void surface_allocate_surface(IWineD3DSurfaceImpl *This, GLenum internal, GLsizei width, GLsizei height, GLenum format, GLenum type) {
250 BOOL enable_client_storage = FALSE;
251 BYTE *mem = NULL;
253 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,
254 This->glDescription.target, This->glDescription.level, debug_d3dformat(This->resource.format), internal, width, height, format, type);
256 if (This->resource.format == WINED3DFMT_DXT1 ||
257 This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
258 This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) {
259 /* glCompressedTexImage2D does not accept NULL pointers, so we cannot allocate a compressed texture without uploading data */
260 TRACE("Not allocating compressed surfaces, surface_upload_data will specify them\n");
262 /* We have to point GL to the client storage memory here, because upload_data might use a PBO. This means a double upload
263 * once, unfortunately
265 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
266 /* Neither NONPOW2, DIBSECTION nor OVERSIZE flags can be set on compressed textures */
267 This->Flags |= SFLAG_CLIENT;
268 mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
269 GL_EXTCALL(glCompressedTexImage2DARB(This->glDescription.target, This->glDescription.level, internal,
270 width, height, 0 /* border */, This->resource.size, mem));
273 return;
276 ENTER_GL();
278 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
279 if(This->Flags & (SFLAG_NONPOW2 | SFLAG_DIBSECTION | SFLAG_OVERSIZE | SFLAG_CONVERTED) || This->resource.allocatedMemory == NULL) {
280 /* In some cases we want to disable client storage.
281 * SFLAG_NONPOW2 has a bigger opengl texture than the client memory, and different pitches
282 * SFLAG_DIBSECTION: Dibsections may have read / write protections on the memory. Avoid issues...
283 * SFLAG_OVERSIZE: The gl texture is smaller than the allocated memory
284 * SFLAG_CONVERTED: The conversion destination memory is freed after loading the surface
285 * allocatedMemory == NULL: Not defined in the extension. Seems to disable client storage effectively
287 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
288 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
289 This->Flags &= ~SFLAG_CLIENT;
290 enable_client_storage = TRUE;
291 } else {
292 This->Flags |= SFLAG_CLIENT;
294 /* Point opengl to our allocated texture memory. Do not use resource.allocatedMemory here because
295 * it might point into a pbo. Instead use heapMemory, but get the alignment right.
297 mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
300 glTexImage2D(This->glDescription.target, This->glDescription.level, internal, width, height, 0, format, type, mem);
301 checkGLcall("glTexImage2D");
303 if(enable_client_storage) {
304 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
305 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
307 LEAVE_GL();
309 This->Flags |= SFLAG_ALLOCATED;
312 /* In D3D the depth stencil dimensions have to be greater than or equal to the
313 * render target dimensions. With FBOs, the dimensions have to be an exact match. */
314 /* TODO: We should synchronize the renderbuffer's content with the texture's content. */
315 void surface_set_compatible_renderbuffer(IWineD3DSurface *iface, unsigned int width, unsigned int height) {
316 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
317 renderbuffer_entry_t *entry;
318 GLuint renderbuffer = 0;
319 unsigned int src_width, src_height;
321 src_width = This->pow2Width;
322 src_height = This->pow2Height;
324 /* A depth stencil smaller than the render target is not valid */
325 if (width > src_width || height > src_height) return;
327 /* Remove any renderbuffer set if the sizes match */
328 if (width == src_width && height == src_height) {
329 This->current_renderbuffer = NULL;
330 return;
333 /* Look if we've already got a renderbuffer of the correct dimensions */
334 LIST_FOR_EACH_ENTRY(entry, &This->renderbuffers, renderbuffer_entry_t, entry) {
335 if (entry->width == width && entry->height == height) {
336 renderbuffer = entry->id;
337 This->current_renderbuffer = entry;
338 break;
342 if (!renderbuffer) {
343 const GlPixelFormatDesc *glDesc;
344 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
346 GL_EXTCALL(glGenRenderbuffersEXT(1, &renderbuffer));
347 GL_EXTCALL(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, renderbuffer));
348 GL_EXTCALL(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, glDesc->glFormat, width, height));
350 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(renderbuffer_entry_t));
351 entry->width = width;
352 entry->height = height;
353 entry->id = renderbuffer;
354 list_add_head(&This->renderbuffers, &entry->entry);
356 This->current_renderbuffer = entry;
359 checkGLcall("set_compatible_renderbuffer");
362 GLenum surface_get_gl_buffer(IWineD3DSurface *iface, IWineD3DSwapChain *swapchain) {
363 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
364 IWineD3DSwapChainImpl *swapchain_impl = (IWineD3DSwapChainImpl *)swapchain;
366 TRACE("(%p) : swapchain %p\n", This, swapchain);
368 if (swapchain_impl->backBuffer && swapchain_impl->backBuffer[0] == iface) {
369 TRACE("Returning GL_BACK\n");
370 return GL_BACK;
371 } else if (swapchain_impl->frontBuffer == iface) {
372 TRACE("Returning GL_FRONT\n");
373 return GL_FRONT;
376 FIXME("Higher back buffer, returning GL_BACK\n");
377 return GL_BACK;
380 ULONG WINAPI IWineD3DSurfaceImpl_Release(IWineD3DSurface *iface) {
381 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
382 ULONG ref = InterlockedDecrement(&This->resource.ref);
383 TRACE("(%p) : Releasing from %d\n", This, ref + 1);
384 if (ref == 0) {
385 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->resource.wineD3DDevice;
386 renderbuffer_entry_t *entry, *entry2;
387 TRACE("(%p) : cleaning up\n", This);
389 if (This->glDescription.textureName != 0) { /* release the openGL texture.. */
391 /* Need a context to destroy the texture. Use the currently active render target, but only if
392 * the primary render target exists. Otherwise lastActiveRenderTarget is garbage, see above.
393 * When destroying the primary rt, Uninit3D will activate a context before doing anything
395 if(device->render_targets && device->render_targets[0]) {
396 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
399 TRACE("Deleting texture %d\n", This->glDescription.textureName);
400 ENTER_GL();
401 glDeleteTextures(1, &This->glDescription.textureName);
402 LEAVE_GL();
405 if(This->Flags & SFLAG_PBO) {
406 /* Delete the PBO */
407 GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
410 if(This->Flags & SFLAG_DIBSECTION) {
411 /* Release the DC */
412 SelectObject(This->hDC, This->dib.holdbitmap);
413 DeleteDC(This->hDC);
414 /* Release the DIB section */
415 DeleteObject(This->dib.DIBsection);
416 This->dib.bitmap_data = NULL;
417 This->resource.allocatedMemory = NULL;
419 if(This->Flags & SFLAG_USERPTR) IWineD3DSurface_SetMem(iface, NULL);
421 HeapFree(GetProcessHeap(), 0, This->palette9);
423 IWineD3DResourceImpl_CleanUp((IWineD3DResource *)iface);
424 if(iface == device->ddraw_primary)
425 device->ddraw_primary = NULL;
427 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
428 GL_EXTCALL(glDeleteRenderbuffersEXT(1, &entry->id));
429 HeapFree(GetProcessHeap(), 0, entry);
432 TRACE("(%p) Released\n", This);
433 HeapFree(GetProcessHeap(), 0, This);
436 return ref;
439 /* ****************************************************
440 IWineD3DSurface IWineD3DResource parts follow
441 **************************************************** */
443 void WINAPI IWineD3DSurfaceImpl_PreLoad(IWineD3DSurface *iface) {
444 /* TODO: check for locks */
445 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
446 IWineD3DBaseTexture *baseTexture = NULL;
447 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
449 TRACE("(%p)Checking to see if the container is a base texture\n", This);
450 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
451 TRACE("Passing to container\n");
452 IWineD3DBaseTexture_PreLoad(baseTexture);
453 IWineD3DBaseTexture_Release(baseTexture);
454 } else {
455 TRACE("(%p) : About to load surface\n", This);
457 if(!device->isInDraw) {
458 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
461 ENTER_GL();
462 glEnable(This->glDescription.target);/* make sure texture support is enabled in this context */
463 if (!This->glDescription.level) {
464 if (!This->glDescription.textureName) {
465 glGenTextures(1, &This->glDescription.textureName);
466 checkGLcall("glGenTextures");
467 TRACE("Surface %p given name %d\n", This, This->glDescription.textureName);
469 glBindTexture(This->glDescription.target, This->glDescription.textureName);
470 checkGLcall("glBindTexture");
471 IWineD3DSurface_LoadTexture(iface, FALSE);
472 /* This is where we should be reducing the amount of GLMemoryUsed */
473 } else if (This->glDescription.textureName) { /* NOTE: the level 0 surface of a mpmapped texture must be loaded first! */
474 /* assume this is a coding error not a real error for now */
475 FIXME("Mipmap surface has a glTexture bound to it!\n");
477 if (This->resource.pool == WINED3DPOOL_DEFAULT) {
478 /* Tell opengl to try and keep this texture in video ram (well mostly) */
479 GLclampf tmp;
480 tmp = 0.9f;
481 glPrioritizeTextures(1, &This->glDescription.textureName, &tmp);
483 LEAVE_GL();
485 return;
488 /* ******************************************************
489 IWineD3DSurface IWineD3DSurface parts follow
490 ****************************************************** */
492 void WINAPI IWineD3DSurfaceImpl_SetGlTextureDesc(IWineD3DSurface *iface, UINT textureName, int target) {
493 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
494 TRACE("(%p) : setting textureName %u, target %i\n", This, textureName, target);
495 if (This->glDescription.textureName == 0 && textureName != 0) {
496 IWineD3DSurface_ModifyLocation(iface, SFLAG_INTEXTURE, FALSE);
497 IWineD3DSurface_AddDirtyRect(iface, NULL);
499 This->glDescription.textureName = textureName;
500 This->glDescription.target = target;
501 This->Flags &= ~SFLAG_ALLOCATED;
504 void WINAPI IWineD3DSurfaceImpl_GetGlDesc(IWineD3DSurface *iface, glDescriptor **glDescription) {
505 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
506 TRACE("(%p) : returning %p\n", This, &This->glDescription);
507 *glDescription = &This->glDescription;
510 /* TODO: think about moving this down to resource? */
511 const void *WINAPI IWineD3DSurfaceImpl_GetData(IWineD3DSurface *iface) {
512 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
513 /* 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 */
514 if (This->resource.pool != WINED3DPOOL_SYSTEMMEM) {
515 FIXME(" (%p)Attempting to get system memory for a non-system memory texture\n", iface);
517 return (CONST void*)(This->resource.allocatedMemory);
520 static void read_from_framebuffer(IWineD3DSurfaceImpl *This, CONST RECT *rect, void *dest, UINT pitch) {
521 IWineD3DSwapChainImpl *swapchain;
522 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
523 BYTE *mem;
524 GLint fmt;
525 GLint type;
526 BYTE *row, *top, *bottom;
527 int i;
528 BOOL bpp;
529 RECT local_rect;
530 BOOL srcIsUpsideDown;
532 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
533 static BOOL warned = FALSE;
534 if(!warned) {
535 ERR("The application tries to lock the render target, but render target locking is disabled\n");
536 warned = TRUE;
538 return;
541 IWineD3DSurface_GetContainer((IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&swapchain);
542 /* Activate the surface. Set it up for blitting now, although not necessarily needed for LockRect.
543 * Certain graphics drivers seem to dislike some enabled states when reading from opengl, the blitting usage
544 * should help here. Furthermore unlockrect will need the context set up for blitting. The context manager will find
545 * context->last_was_blit set on the unlock.
547 ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
548 ENTER_GL();
550 /* Select the correct read buffer, and give some debug output.
551 * There is no need to keep track of the current read buffer or reset it, every part of the code
552 * that reads sets the read buffer as desired.
554 if(!swapchain) {
555 /* Locking the primary render target which is not on a swapchain(=offscreen render target).
556 * Read from the back buffer
558 TRACE("Locking offscreen render target\n");
559 glReadBuffer(myDevice->offscreenBuffer);
560 srcIsUpsideDown = TRUE;
561 } else {
562 GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *) This, (IWineD3DSwapChain *)swapchain);
563 TRACE("Locking %#x buffer\n", buffer);
564 glReadBuffer(buffer);
565 checkGLcall("glReadBuffer");
567 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
568 srcIsUpsideDown = FALSE;
571 /* TODO: Get rid of the extra rectangle comparison and construction of a full surface rectangle */
572 if(!rect) {
573 local_rect.left = 0;
574 local_rect.top = 0;
575 local_rect.right = This->currentDesc.Width;
576 local_rect.bottom = This->currentDesc.Height;
577 } else {
578 local_rect = *rect;
580 /* TODO: Get rid of the extra GetPitch call, LockRect does that too. Cache the pitch */
582 switch(This->resource.format)
584 case WINED3DFMT_P8:
586 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
587 /* In case of P8 render targets the index is stored in the alpha component */
588 fmt = GL_ALPHA;
589 type = GL_UNSIGNED_BYTE;
590 mem = dest;
591 bpp = This->bytesPerPixel;
592 } else {
593 /* GL can't return palettized data, so read ARGB pixels into a
594 * separate block of memory and convert them into palettized format
595 * in software. Slow, but if the app means to use palettized render
596 * targets and locks it...
598 * Use GL_RGB, GL_UNSIGNED_BYTE to read the surface for performance reasons
599 * Don't use GL_BGR as in the WINED3DFMT_R8G8B8 case, instead watch out
600 * for the color channels when palettizing the colors.
602 fmt = GL_RGB;
603 type = GL_UNSIGNED_BYTE;
604 pitch *= 3;
605 mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * 3);
606 if(!mem) {
607 ERR("Out of memory\n");
608 LEAVE_GL();
609 return;
611 bpp = This->bytesPerPixel * 3;
614 break;
616 default:
617 mem = dest;
618 fmt = This->glDescription.glFormat;
619 type = This->glDescription.glType;
620 bpp = This->bytesPerPixel;
623 if(This->Flags & SFLAG_PBO) {
624 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
625 checkGLcall("glBindBufferARB");
628 glReadPixels(local_rect.left, local_rect.top,
629 local_rect.right - local_rect.left,
630 local_rect.bottom - local_rect.top,
631 fmt, type, mem);
632 vcheckGLcall("glReadPixels");
634 if(This->Flags & SFLAG_PBO) {
635 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
636 checkGLcall("glBindBufferARB");
638 /* Check if we need to flip the image. If we need to flip use glMapBufferARB
639 * to get a pointer to it and perform the flipping in software. This is a lot
640 * faster than calling glReadPixels for each line. In case we want more speed
641 * we should rerender it flipped in a FBO and read the data back from the FBO. */
642 if(!srcIsUpsideDown) {
643 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
644 checkGLcall("glBindBufferARB");
646 mem = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
647 checkGLcall("glMapBufferARB");
651 /* TODO: Merge this with the palettization loop below for P8 targets */
652 if(!srcIsUpsideDown) {
653 UINT len, off;
654 /* glReadPixels returns the image upside down, and there is no way to prevent this.
655 Flip the lines in software */
656 len = (local_rect.right - local_rect.left) * bpp;
657 off = local_rect.left * bpp;
659 row = HeapAlloc(GetProcessHeap(), 0, len);
660 if(!row) {
661 ERR("Out of memory\n");
662 if(This->resource.format == WINED3DFMT_P8) HeapFree(GetProcessHeap(), 0, mem);
663 LEAVE_GL();
664 return;
667 top = mem + pitch * local_rect.top;
668 bottom = ((BYTE *) mem) + pitch * ( local_rect.bottom - local_rect.top - 1);
669 for(i = 0; i < (local_rect.bottom - local_rect.top) / 2; i++) {
670 memcpy(row, top + off, len);
671 memcpy(top + off, bottom + off, len);
672 memcpy(bottom + off, row, len);
673 top += pitch;
674 bottom -= pitch;
676 HeapFree(GetProcessHeap(), 0, row);
678 /* Unmap the temp PBO buffer */
679 if(This->Flags & SFLAG_PBO) {
680 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
681 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
685 /* For P8 textures we need to perform an inverse palette lookup. This is done by searching for a palette
686 * index which matches the RGB value. Note this isn't guaranteed to work when there are multiple entries for
687 * the same color but we have no choice.
688 * In case of render targets, the index is stored in the alpha component so no conversion is needed.
690 if((This->resource.format == WINED3DFMT_P8) && !(This->resource.usage & WINED3DUSAGE_RENDERTARGET)) {
691 PALETTEENTRY *pal;
692 DWORD width = pitch / 3;
693 int x, y, c;
694 if(This->palette) {
695 pal = This->palette->palents;
696 } else {
697 pal = This->resource.wineD3DDevice->palettes[This->resource.wineD3DDevice->currentPalette];
700 for(y = local_rect.top; y < local_rect.bottom; y++) {
701 for(x = local_rect.left; x < local_rect.right; x++) {
702 /* start lines pixels */
703 BYTE *blue = (BYTE *) ((BYTE *) mem) + y * pitch + x * (sizeof(BYTE) * 3);
704 BYTE *green = blue + 1;
705 BYTE *red = green + 1;
707 for(c = 0; c < 256; c++) {
708 if(*red == pal[c].peRed &&
709 *green == pal[c].peGreen &&
710 *blue == pal[c].peBlue)
712 *((BYTE *) dest + y * width + x) = c;
713 break;
718 HeapFree(GetProcessHeap(), 0, mem);
720 LEAVE_GL();
723 static void surface_prepare_system_memory(IWineD3DSurfaceImpl *This) {
724 /* Performance optimization: Count how often a surface is locked, if it is locked regularly do not throw away the system memory copy.
725 * This avoids the need to download the surface from opengl all the time. The surface is still downloaded if the opengl texture is
726 * changed
728 if(!(This->Flags & SFLAG_DYNLOCK)) {
729 This->lockCount++;
730 /* MAXLOCKCOUNT is defined in wined3d_private.h */
731 if(This->lockCount > MAXLOCKCOUNT) {
732 TRACE("Surface is locked regularly, not freeing the system memory copy any more\n");
733 This->Flags |= SFLAG_DYNLOCK;
737 /* Create a PBO for dynamically locked surfaces but don't do it for converted or non-pow2 surfaces.
738 * Also don't create a PBO for systemmem surfaces.
740 if(GL_SUPPORT(ARB_PIXEL_BUFFER_OBJECT) && (This->Flags & SFLAG_DYNLOCK) && !(This->Flags & (SFLAG_PBO | SFLAG_CONVERTED | SFLAG_NONPOW2)) && (This->resource.pool != WINED3DPOOL_SYSTEMMEM)) {
741 GLenum error;
742 ENTER_GL();
744 GL_EXTCALL(glGenBuffersARB(1, &This->pbo));
745 error = glGetError();
746 if(This->pbo == 0 || error != GL_NO_ERROR) {
747 ERR("Failed to bind the PBO with error %s (%#x)\n", debug_glerror(error), error);
750 TRACE("Attaching pbo=%#x to (%p)\n", This->pbo, This);
752 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
753 checkGLcall("glBindBufferARB");
755 GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->resource.size + 4, This->resource.allocatedMemory, GL_STREAM_DRAW_ARB));
756 checkGLcall("glBufferDataARB");
758 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
759 checkGLcall("glBindBufferARB");
761 /* We don't need the system memory anymore and we can't even use it for PBOs */
762 if(!(This->Flags & SFLAG_CLIENT)) {
763 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
764 This->resource.heapMemory = NULL;
766 This->resource.allocatedMemory = NULL;
767 This->Flags |= SFLAG_PBO;
768 LEAVE_GL();
769 } else if(!(This->resource.allocatedMemory || This->Flags & SFLAG_PBO)) {
770 /* Whatever surface we have, make sure that there is memory allocated for the downloaded copy,
771 * or a pbo to map
773 if(!This->resource.heapMemory) {
774 This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
776 This->resource.allocatedMemory =
777 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
778 if(This->Flags & SFLAG_INSYSMEM) {
779 ERR("Surface without memory or pbo has SFLAG_INSYSMEM set!\n");
784 static HRESULT WINAPI IWineD3DSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags) {
785 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
786 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
787 IWineD3DSwapChain *swapchain = NULL;
789 TRACE("(%p) : rect@%p flags(%08x), output lockedRect@%p, memory@%p\n", This, pRect, Flags, pLockedRect, This->resource.allocatedMemory);
791 /* This is also done in the base class, but we have to verify this before loading any data from
792 * gl into the sysmem copy. The PBO may be mapped, a different rectangle locked, the discard flag
793 * may interfere, and all other bad things may happen
795 if (This->Flags & SFLAG_LOCKED) {
796 WARN("Surface is already locked, returning D3DERR_INVALIDCALL\n");
797 return WINED3DERR_INVALIDCALL;
799 This->Flags |= SFLAG_LOCKED;
801 if (!(This->Flags & SFLAG_LOCKABLE))
803 TRACE("Warning: trying to lock unlockable surf@%p\n", This);
806 if (Flags & WINED3DLOCK_DISCARD) {
807 /* Set SFLAG_INSYSMEM, so we'll never try to download the data from the texture. */
808 TRACE("WINED3DLOCK_DISCARD flag passed, marking local copy as up to date\n");
809 This->Flags |= SFLAG_INSYSMEM;
812 if (This->Flags & SFLAG_INSYSMEM) {
813 TRACE("Local copy is up to date, not downloading data\n");
814 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
815 goto lock_end;
818 /* Now download the surface content from opengl
819 * Use the render target readback if the surface is on a swapchain(=onscreen render target) or the current primary target
820 * Offscreen targets which are not active at the moment or are higher targets(fbos) can be locked with the texture path
822 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain);
823 if(swapchain || iface == myDevice->render_targets[0]) {
824 const RECT *pass_rect = pRect;
826 /* IWineD3DSurface_LoadLocation does not check if the rectangle specifies the full surfaces
827 * because most caller functions do not need that. So do that here
829 if(pRect &&
830 pRect->top == 0 &&
831 pRect->left == 0 &&
832 pRect->right == This->currentDesc.Width &&
833 pRect->bottom == This->currentDesc.Height) {
834 pass_rect = NULL;
837 switch(wined3d_settings.rendertargetlock_mode) {
838 case RTL_TEXDRAW:
839 case RTL_TEXTEX:
840 FIXME("Reading from render target with a texture isn't implemented yet, falling back to framebuffer reading\n");
841 #if 0
842 /* Disabled for now. LoadLocation prefers the texture over the drawable as the source. So if we copy to the
843 * texture first, then to sysmem, we'll avoid glReadPixels and use glCopyTexImage and glGetTexImage2D instead.
844 * This may be faster on some cards
846 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* No partial texture copy yet */);
847 #endif
848 /* drop through */
850 case RTL_AUTO:
851 case RTL_READDRAW:
852 case RTL_READTEX:
853 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, pRect);
854 break;
856 case RTL_DISABLE:
857 break;
859 if(swapchain) IWineD3DSwapChain_Release(swapchain);
861 } else if(iface == myDevice->stencilBufferTarget) {
862 /** the depth stencil in openGL has a format of GL_FLOAT
863 * which should be good for WINED3DFMT_D16_LOCKABLE
864 * and WINED3DFMT_D16
865 * it is unclear what format the stencil buffer is in except.
866 * 'Each index is converted to fixed point...
867 * If GL_MAP_STENCIL is GL_TRUE, indices are replaced by their
868 * mappings in the table GL_PIXEL_MAP_S_TO_S.
869 * glReadPixels(This->lockedRect.left,
870 * This->lockedRect.bottom - j - 1,
871 * This->lockedRect.right - This->lockedRect.left,
872 * 1,
873 * GL_DEPTH_COMPONENT,
874 * type,
875 * (char *)pLockedRect->pBits + (pLockedRect->Pitch * (j-This->lockedRect.top)));
877 * Depth Stencil surfaces which are not the current depth stencil target should have their data in a
878 * gl texture(next path), or in local memory(early return because of set SFLAG_INSYSMEM above). If
879 * none of that is the case the problem is not in this function :-)
880 ********************************************/
881 FIXME("Depth stencil locking not supported yet\n");
882 } else {
883 /* This path is for normal surfaces, offscreen render targets and everything else that is in a gl texture */
884 TRACE("locking an ordinary surface\n");
885 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL /* no partial locking for textures yet */);
888 lock_end:
889 if(This->Flags & SFLAG_PBO) {
890 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
891 ENTER_GL();
892 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
893 checkGLcall("glBindBufferARB");
895 /* This shouldn't happen but could occur if some other function didn't handle the PBO properly */
896 if(This->resource.allocatedMemory) {
897 ERR("The surface already has PBO memory allocated!\n");
900 This->resource.allocatedMemory = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
901 checkGLcall("glMapBufferARB");
903 /* Make sure the pbo isn't set anymore in order not to break non-pbo calls */
904 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
905 checkGLcall("glBindBufferARB");
907 LEAVE_GL();
910 if (Flags & (WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY)) {
911 /* Don't dirtify */
912 } else {
913 IWineD3DBaseTexture *pBaseTexture;
915 * Dirtify on lock
916 * as seen in msdn docs
918 IWineD3DSurface_AddDirtyRect(iface, pRect);
920 /** Dirtify Container if needed */
921 if (WINED3D_OK == IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&pBaseTexture) && pBaseTexture != NULL) {
922 TRACE("Making container dirty\n");
923 IWineD3DBaseTexture_SetDirty(pBaseTexture, TRUE);
924 IWineD3DBaseTexture_Release(pBaseTexture);
925 } else {
926 TRACE("Surface is standalone, no need to dirty the container\n");
930 return IWineD3DBaseSurfaceImpl_LockRect(iface, pLockedRect, pRect, Flags);
933 static void flush_to_framebuffer_drawpixels(IWineD3DSurfaceImpl *This) {
934 GLint prev_store;
935 GLint prev_rasterpos[4];
936 GLint skipBytes = 0;
937 BOOL storechanged = FALSE, memory_allocated = FALSE;
938 GLint fmt, type;
939 BYTE *mem;
940 UINT bpp;
941 UINT pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This); /* target is argb, 4 byte */
942 IWineD3DDeviceImpl *myDevice = (IWineD3DDeviceImpl *) This->resource.wineD3DDevice;
943 IWineD3DSwapChainImpl *swapchain;
945 /* Activate the correct context for the render target */
946 ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
947 ENTER_GL();
949 IWineD3DSurface_GetContainer((IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&swapchain);
950 if(!swapchain) {
951 /* Primary offscreen render target */
952 TRACE("Offscreen render target\n");
953 glDrawBuffer(myDevice->offscreenBuffer);
954 checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
955 } else {
956 GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *) This, (IWineD3DSwapChain *)swapchain);
957 TRACE("Unlocking %#x buffer\n", buffer);
958 glDrawBuffer(buffer);
959 checkGLcall("glDrawBuffer");
961 IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapchain);
964 glFlush();
965 vcheckGLcall("glFlush");
966 glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
967 vcheckGLcall("glIntegerv");
968 glGetIntegerv(GL_CURRENT_RASTER_POSITION, &prev_rasterpos[0]);
969 vcheckGLcall("glIntegerv");
970 glPixelZoom(1.0, -1.0);
971 vcheckGLcall("glPixelZoom");
973 /* If not fullscreen, we need to skip a number of bytes to find the next row of data */
974 glGetIntegerv(GL_UNPACK_ROW_LENGTH, &skipBytes);
975 glPixelStorei(GL_UNPACK_ROW_LENGTH, This->currentDesc.Width);
977 glRasterPos3i(This->lockedRect.left, This->lockedRect.top, 1);
978 vcheckGLcall("glRasterPos2f");
980 /* Some drivers(radeon dri, others?) don't like exceptions during
981 * glDrawPixels. If the surface is a DIB section, it might be in GDIMode
982 * after ReleaseDC. Reading it will cause an exception, which x11drv will
983 * catch to put the dib section in InSync mode, which leads to a crash
984 * and a blocked x server on my radeon card.
986 * The following lines read the dib section so it is put in inSync mode
987 * before glDrawPixels is called and the crash is prevented. There won't
988 * be any interfering gdi accesses, because UnlockRect is called from
989 * ReleaseDC, and the app won't use the dc any more afterwards.
991 if((This->Flags & SFLAG_DIBSECTION) && !(This->Flags & SFLAG_PBO)) {
992 volatile BYTE read;
993 read = This->resource.allocatedMemory[0];
996 switch (This->resource.format) {
997 /* No special care needed */
998 case WINED3DFMT_A4R4G4B4:
999 case WINED3DFMT_R5G6B5:
1000 case WINED3DFMT_A1R5G5B5:
1001 case WINED3DFMT_R8G8B8:
1002 case WINED3DFMT_X4R4G4B4:
1003 case WINED3DFMT_X1R5G5B5:
1004 type = This->glDescription.glType;
1005 fmt = This->glDescription.glFormat;
1006 mem = This->resource.allocatedMemory;
1007 bpp = This->bytesPerPixel;
1008 break;
1010 /* In the past times we used to set the X channel of X8R8G8B8 and the above formats to
1011 * 1.0 because it happened to fix the intro movie in Pirates. However, this seems wrong.
1012 * If the game uses an X8R8G8B8 back buffer the GL alpha channel should not make any differences,
1013 * and the bug must be somewhere else. If we really have to set the alpha channel to 1.0 in
1014 * this case do it by clearing it after the draw instead of fixing it up in the CPU. Blending
1015 * is disabled via CTXUSAGE_BLIT context setup, so in the glDrawPixels call it does not
1016 * have any effects
1018 case WINED3DFMT_X8R8G8B8:
1019 case WINED3DFMT_A8R8G8B8:
1021 glPixelStorei(GL_PACK_SWAP_BYTES, TRUE);
1022 vcheckGLcall("glPixelStorei");
1023 storechanged = TRUE;
1024 type = This->glDescription.glType;
1025 fmt = This->glDescription.glFormat;
1026 mem = This->resource.allocatedMemory;
1027 bpp = This->bytesPerPixel;
1029 break;
1031 case WINED3DFMT_A2R10G10B10:
1033 glPixelStorei(GL_PACK_SWAP_BYTES, TRUE);
1034 vcheckGLcall("glPixelStorei");
1035 storechanged = TRUE;
1036 type = This->glDescription.glType;
1037 fmt = This->glDescription.glFormat;
1038 mem = This->resource.allocatedMemory;
1039 bpp = This->bytesPerPixel;
1041 break;
1043 case WINED3DFMT_P8:
1045 int height = This->glRect.bottom - This->glRect.top;
1046 type = GL_UNSIGNED_BYTE;
1047 fmt = GL_RGBA;
1049 mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * sizeof(DWORD));
1050 if(!mem) {
1051 ERR("Out of memory\n");
1052 goto cleanup;
1054 memory_allocated = TRUE;
1055 d3dfmt_convert_surface(This->resource.allocatedMemory,
1056 mem,
1057 pitch,
1058 pitch,
1059 height,
1060 pitch * 4,
1061 CONVERT_PALETTED,
1062 This);
1063 bpp = This->bytesPerPixel * 4;
1064 pitch *= 4;
1066 break;
1068 default:
1069 FIXME("Unsupported Format %u in locking func\n", This->resource.format);
1071 /* Give it a try */
1072 type = This->glDescription.glType;
1073 fmt = This->glDescription.glFormat;
1074 mem = This->resource.allocatedMemory;
1075 bpp = This->bytesPerPixel;
1078 if(This->Flags & SFLAG_PBO) {
1079 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1080 checkGLcall("glBindBufferARB");
1083 glDrawPixels(This->lockedRect.right - This->lockedRect.left,
1084 (This->lockedRect.bottom - This->lockedRect.top)-1,
1085 fmt, type,
1086 mem + bpp * This->lockedRect.left + pitch * This->lockedRect.top);
1087 checkGLcall("glDrawPixels");
1089 cleanup:
1090 if(This->Flags & SFLAG_PBO) {
1091 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1092 checkGLcall("glBindBufferARB");
1095 glPixelZoom(1.0,1.0);
1096 vcheckGLcall("glPixelZoom");
1098 glRasterPos3iv(&prev_rasterpos[0]);
1099 vcheckGLcall("glRasterPos3iv");
1101 /* Reset to previous pack row length */
1102 glPixelStorei(GL_UNPACK_ROW_LENGTH, skipBytes);
1103 vcheckGLcall("glPixelStorei GL_UNPACK_ROW_LENGTH");
1104 if(storechanged) {
1105 glPixelStorei(GL_PACK_SWAP_BYTES, prev_store);
1106 vcheckGLcall("glPixelStorei GL_PACK_SWAP_BYTES");
1109 if(memory_allocated) HeapFree(GetProcessHeap(), 0, mem);
1111 if(!swapchain) {
1112 glDrawBuffer(myDevice->offscreenBuffer);
1113 checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
1114 } else if(swapchain->backBuffer) {
1115 glDrawBuffer(GL_BACK);
1116 checkGLcall("glDrawBuffer(GL_BACK)");
1117 } else {
1118 glDrawBuffer(GL_FRONT);
1119 checkGLcall("glDrawBuffer(GL_FRONT)");
1121 LEAVE_GL();
1123 return;
1126 static HRESULT WINAPI IWineD3DSurfaceImpl_UnlockRect(IWineD3DSurface *iface) {
1127 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1128 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
1129 IWineD3DSwapChainImpl *swapchain = NULL;
1130 BOOL fullsurface;
1132 if (!(This->Flags & SFLAG_LOCKED)) {
1133 WARN("trying to Unlock an unlocked surf@%p\n", This);
1134 return WINED3DERR_INVALIDCALL;
1137 if (This->Flags & SFLAG_PBO) {
1138 TRACE("Freeing PBO memory\n");
1139 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
1140 ENTER_GL();
1141 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1142 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1143 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1144 checkGLcall("glUnmapBufferARB");
1145 LEAVE_GL();
1146 This->resource.allocatedMemory = NULL;
1149 TRACE("(%p) : dirtyfied(%d)\n", This, This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
1151 if (This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE)) {
1152 TRACE("(%p) : Not Dirtified so nothing to do, return now\n", This);
1153 goto unlock_end;
1156 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain);
1157 if(swapchain || (myDevice->render_targets && iface == myDevice->render_targets[0])) {
1158 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1159 static BOOL warned = FALSE;
1160 if(!warned) {
1161 ERR("The application tries to write to the render target, but render target locking is disabled\n");
1162 warned = TRUE;
1164 if(swapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
1165 goto unlock_end;
1168 if(This->dirtyRect.left == 0 &&
1169 This->dirtyRect.top == 0 &&
1170 This->dirtyRect.right == This->currentDesc.Width &&
1171 This->dirtyRect.bottom == This->currentDesc.Height) {
1172 fullsurface = TRUE;
1173 } else {
1174 /* TODO: Proper partial rectangle tracking */
1175 fullsurface = FALSE;
1176 This->Flags |= SFLAG_INSYSMEM;
1179 switch(wined3d_settings.rendertargetlock_mode) {
1180 case RTL_READTEX:
1181 case RTL_TEXTEX:
1182 ActivateContext(myDevice, iface, CTXUSAGE_BLIT);
1183 ENTER_GL();
1184 if (This->glDescription.textureName == 0) {
1185 glGenTextures(1, &This->glDescription.textureName);
1186 checkGLcall("glGenTextures");
1188 glBindTexture(This->glDescription.target, This->glDescription.textureName);
1189 checkGLcall("glBindTexture(This->glDescription.target, This->glDescription.textureName)");
1190 LEAVE_GL();
1191 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* partial texture loading not supported yet */);
1192 /* drop through */
1194 case RTL_AUTO:
1195 case RTL_READDRAW:
1196 case RTL_TEXDRAW:
1197 IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, fullsurface ? NULL : &This->dirtyRect);
1198 break;
1201 if(!fullsurface) {
1202 /* Partial rectangle tracking is not commonly implemented, it is only done for render targets. Overwrite
1203 * the flags to bring them back into a sane state. INSYSMEM was set before to tell LoadLocation where
1204 * to read the rectangle from. Indrawable is set because all modifications from the partial sysmem copy
1205 * are written back to the drawable, thus the surface is merged again in the drawable. The sysmem copy is
1206 * not fully up to date because only a subrectangle was read in LockRect.
1208 This->Flags &= ~SFLAG_INSYSMEM;
1209 This->Flags |= SFLAG_INDRAWABLE;
1212 This->dirtyRect.left = This->currentDesc.Width;
1213 This->dirtyRect.top = This->currentDesc.Height;
1214 This->dirtyRect.right = 0;
1215 This->dirtyRect.bottom = 0;
1216 } else if(iface == myDevice->stencilBufferTarget) {
1217 FIXME("Depth Stencil buffer locking is not implemented\n");
1218 } else {
1219 /* The rest should be a normal texture */
1220 IWineD3DBaseTextureImpl *impl;
1221 /* Check if the texture is bound, if yes dirtify the sampler to force a re-upload of the texture
1222 * Can't load the texture here because PreLoad may destroy and recreate the gl texture, so sampler
1223 * states need resetting
1225 if(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&impl) == WINED3D_OK) {
1226 if(impl->baseTexture.bindCount) {
1227 IWineD3DDeviceImpl_MarkStateDirty(myDevice, STATE_SAMPLER(impl->baseTexture.sampler));
1229 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *) impl);
1233 unlock_end:
1234 This->Flags &= ~SFLAG_LOCKED;
1235 memset(&This->lockedRect, 0, sizeof(RECT));
1236 return WINED3D_OK;
1239 HRESULT WINAPI IWineD3DSurfaceImpl_GetDC(IWineD3DSurface *iface, HDC *pHDC) {
1240 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1241 WINED3DLOCKED_RECT lock;
1242 HRESULT hr;
1243 RGBQUAD col[256];
1245 TRACE("(%p)->(%p)\n",This,pHDC);
1247 if(This->Flags & SFLAG_USERPTR) {
1248 ERR("Not supported on surfaces with an application-provided surfaces\n");
1249 return WINEDDERR_NODC;
1252 /* Give more detailed info for ddraw */
1253 if (This->Flags & SFLAG_DCINUSE)
1254 return WINEDDERR_DCALREADYCREATED;
1256 /* Can't GetDC if the surface is locked */
1257 if (This->Flags & SFLAG_LOCKED)
1258 return WINED3DERR_INVALIDCALL;
1260 memset(&lock, 0, sizeof(lock)); /* To be sure */
1262 /* Create a DIB section if there isn't a hdc yet */
1263 if(!This->hDC) {
1264 IWineD3DBaseSurfaceImpl_CreateDIBSection(iface);
1265 if(This->Flags & SFLAG_CLIENT) {
1266 IWineD3DSurface_PreLoad(iface);
1269 /* Use the dib section from now on if we are not using a PBO */
1270 if(!(This->Flags & SFLAG_PBO))
1271 This->resource.allocatedMemory = This->dib.bitmap_data;
1274 /* Lock the surface */
1275 hr = IWineD3DSurface_LockRect(iface,
1276 &lock,
1277 NULL,
1280 if(This->Flags & SFLAG_PBO) {
1281 /* Sync the DIB with the PBO. This can't be done earlier because LockRect activates the allocatedMemory */
1282 memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, This->dib.bitmap_size);
1285 if(FAILED(hr)) {
1286 ERR("IWineD3DSurface_LockRect failed with hr = %08x\n", hr);
1287 /* keep the dib section */
1288 return hr;
1291 if(This->resource.format == WINED3DFMT_P8 ||
1292 This->resource.format == WINED3DFMT_A8P8) {
1293 unsigned int n;
1294 if(This->palette) {
1295 PALETTEENTRY ent[256];
1297 GetPaletteEntries(This->palette->hpal, 0, 256, ent);
1298 for (n=0; n<256; n++) {
1299 col[n].rgbRed = ent[n].peRed;
1300 col[n].rgbGreen = ent[n].peGreen;
1301 col[n].rgbBlue = ent[n].peBlue;
1302 col[n].rgbReserved = 0;
1304 } else {
1305 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1307 for (n=0; n<256; n++) {
1308 col[n].rgbRed = device->palettes[device->currentPalette][n].peRed;
1309 col[n].rgbGreen = device->palettes[device->currentPalette][n].peGreen;
1310 col[n].rgbBlue = device->palettes[device->currentPalette][n].peBlue;
1311 col[n].rgbReserved = 0;
1315 SetDIBColorTable(This->hDC, 0, 256, col);
1318 *pHDC = This->hDC;
1319 TRACE("returning %p\n",*pHDC);
1320 This->Flags |= SFLAG_DCINUSE;
1322 return WINED3D_OK;
1325 HRESULT WINAPI IWineD3DSurfaceImpl_ReleaseDC(IWineD3DSurface *iface, HDC hDC) {
1326 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1328 TRACE("(%p)->(%p)\n",This,hDC);
1330 if (!(This->Flags & SFLAG_DCINUSE))
1331 return WINED3DERR_INVALIDCALL;
1333 if (This->hDC !=hDC) {
1334 WARN("Application tries to release an invalid DC(%p), surface dc is %p\n", hDC, This->hDC);
1335 return WINED3DERR_INVALIDCALL;
1338 if((This->Flags & SFLAG_PBO) && This->resource.allocatedMemory) {
1339 /* Copy the contents of the DIB over to the PBO */
1340 memcpy(This->resource.allocatedMemory, This->dib.bitmap_data, This->dib.bitmap_size);
1343 /* we locked first, so unlock now */
1344 IWineD3DSurface_UnlockRect(iface);
1346 This->Flags &= ~SFLAG_DCINUSE;
1348 return WINED3D_OK;
1351 /* ******************************************************
1352 IWineD3DSurface Internal (No mapping to directx api) parts follow
1353 ****************************************************** */
1355 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) {
1356 BOOL colorkey_active = need_alpha_ck && (This->CKeyFlags & WINEDDSD_CKSRCBLT);
1357 const GlPixelFormatDesc *glDesc;
1358 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1359 BOOL p8_render_target = FALSE;
1360 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
1362 /* Default values: From the surface */
1363 *format = glDesc->glFormat;
1364 *type = glDesc->glType;
1365 *convert = NO_CONVERSION;
1366 *target_bpp = This->bytesPerPixel;
1368 if(srgb_mode) {
1369 *internal = glDesc->glGammaInternal;
1370 } else if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
1371 *internal = glDesc->rtInternal;
1372 } else {
1373 *internal = glDesc->glInternal;
1376 /* Ok, now look if we have to do any conversion */
1377 switch(This->resource.format) {
1378 case WINED3DFMT_P8:
1379 /* ****************
1380 Paletted Texture
1381 **************** */
1383 if (device->render_targets && device->render_targets[0]) {
1384 IWineD3DSurfaceImpl* render_target = (IWineD3DSurfaceImpl*)device->render_targets[0];
1385 if((render_target->resource.usage & WINED3DUSAGE_RENDERTARGET) && (render_target->resource.format == WINED3DFMT_P8))
1386 p8_render_target = TRUE;
1389 /* Use conversion when the paletted texture extension is not available, or when it is available make sure it is used
1390 * for texturing as it won't work for calls like glDraw-/glReadPixels and further also use conversion in case of color keying.
1391 * Paletted textures can be emulated using shaders but only do that for 2D purposes e.g. situations in which the main render target uses p8. Some games like GTA Vice City use P8 for texturing which conflicts with this.
1393 if( !(GL_SUPPORT(EXT_PALETTED_TEXTURE) || (GL_SUPPORT(ARB_FRAGMENT_PROGRAM) && p8_render_target)) || colorkey_active || (!use_texturing && GL_SUPPORT(EXT_PALETTED_TEXTURE)) ) {
1394 *format = GL_RGBA;
1395 *internal = GL_RGBA;
1396 *type = GL_UNSIGNED_BYTE;
1397 *target_bpp = 4;
1398 if(colorkey_active) {
1399 *convert = CONVERT_PALETTED_CK;
1400 } else {
1401 *convert = CONVERT_PALETTED;
1404 else if(!GL_SUPPORT(EXT_PALETTED_TEXTURE) && GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
1405 *format = GL_RED;
1406 *internal = GL_RGBA;
1407 *type = GL_UNSIGNED_BYTE;
1408 *target_bpp = 1;
1411 break;
1413 case WINED3DFMT_R3G3B2:
1414 /* **********************
1415 GL_UNSIGNED_BYTE_3_3_2
1416 ********************** */
1417 if (colorkey_active) {
1418 /* This texture format will never be used.. So do not care about color keying
1419 up until the point in time it will be needed :-) */
1420 FIXME(" ColorKeying not supported in the RGB 332 format !\n");
1422 break;
1424 case WINED3DFMT_R5G6B5:
1425 if (colorkey_active) {
1426 *convert = CONVERT_CK_565;
1427 *format = GL_RGBA;
1428 *internal = GL_RGBA;
1429 *type = GL_UNSIGNED_SHORT_5_5_5_1;
1431 break;
1433 case WINED3DFMT_X1R5G5B5:
1434 if (colorkey_active) {
1435 *convert = CONVERT_CK_5551;
1436 *format = GL_BGRA;
1437 *internal = GL_RGBA;
1438 *type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
1440 break;
1442 case WINED3DFMT_R8G8B8:
1443 if (colorkey_active) {
1444 *convert = CONVERT_CK_RGB24;
1445 *format = GL_RGBA;
1446 *internal = GL_RGBA;
1447 *type = GL_UNSIGNED_INT_8_8_8_8;
1448 *target_bpp = 4;
1450 break;
1452 case WINED3DFMT_X8R8G8B8:
1453 if (colorkey_active) {
1454 *convert = CONVERT_RGB32_888;
1455 *format = GL_RGBA;
1456 *internal = GL_RGBA;
1457 *type = GL_UNSIGNED_INT_8_8_8_8;
1459 break;
1461 case WINED3DFMT_V8U8:
1462 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1463 else if(GL_SUPPORT(ATI_ENVMAP_BUMPMAP)) {
1464 *format = GL_DUDV_ATI;
1465 *internal = GL_DU8DV8_ATI;
1466 *type = GL_BYTE;
1467 /* No conversion - Just change the gl type */
1468 break;
1470 *convert = CONVERT_V8U8;
1471 *format = GL_BGR;
1472 *internal = GL_RGB8;
1473 *type = GL_UNSIGNED_BYTE;
1474 *target_bpp = 3;
1475 break;
1477 case WINED3DFMT_L6V5U5:
1478 *convert = CONVERT_L6V5U5;
1479 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1480 *target_bpp = 3;
1481 /* Use format and types from table */
1482 } else {
1483 /* Load it into unsigned R5G6B5, swap L and V channels, and revert that in the shader */
1484 *target_bpp = 2;
1485 *format = GL_RGB;
1486 *internal = GL_RGB5;
1487 *type = GL_UNSIGNED_SHORT_5_6_5;
1489 break;
1491 case WINED3DFMT_X8L8V8U8:
1492 *convert = CONVERT_X8L8V8U8;
1493 *target_bpp = 4;
1494 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1495 /* Use formats from gl table. It is a bit unfortunate, but the conversion
1496 * is needed to set the X format to 255 to get 1.0 for alpha when sampling
1497 * the texture. OpenGL can't use GL_DSDT8_MAG8_NV as internal format with
1498 * the needed type and format parameter, so the internal format contains a
1499 * 4th component, which is returned as alpha
1501 } else {
1502 /* Not supported by GL_ATI_envmap_bumpmap */
1503 *format = GL_BGRA;
1504 *internal = GL_RGB8;
1505 *type = GL_UNSIGNED_INT_8_8_8_8_REV;
1507 break;
1509 case WINED3DFMT_Q8W8V8U8:
1510 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1511 *convert = CONVERT_Q8W8V8U8;
1512 *format = GL_BGRA;
1513 *internal = GL_RGBA8;
1514 *type = GL_UNSIGNED_BYTE;
1515 *target_bpp = 4;
1516 /* Not supported by GL_ATI_envmap_bumpmap */
1517 break;
1519 case WINED3DFMT_V16U16:
1520 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1521 *convert = CONVERT_V16U16;
1522 *format = GL_BGR;
1523 *internal = GL_RGB16_EXT;
1524 *type = GL_UNSIGNED_SHORT;
1525 *target_bpp = 6;
1526 /* What should I do here about GL_ATI_envmap_bumpmap?
1527 * Convert it or allow data loss by loading it into a 8 bit / channel texture?
1529 break;
1531 case WINED3DFMT_A4L4:
1532 /* A4L4 exists as an internal gl format, but for some reason there is not
1533 * format+type combination to load it. Thus convert it to A8L8, then load it
1534 * with A4L4 internal, but A8L8 format+type
1536 *convert = CONVERT_A4L4;
1537 *format = GL_LUMINANCE_ALPHA;
1538 *internal = GL_LUMINANCE4_ALPHA4;
1539 *type = GL_UNSIGNED_BYTE;
1540 *target_bpp = 2;
1541 break;
1543 case WINED3DFMT_R32F:
1544 /* Can be loaded in theory with fmt=GL_RED, type=GL_FLOAT, but this fails. The reason
1545 * is that D3D expects the undefined green, blue and alpha channels to return 1.0
1546 * when sampling, but OpenGL sets green and blue to 0.0 instead. Thus we have to inject
1547 * 1.0 instead.
1549 * The alpha channel defaults to 1.0 in opengl, so nothing has to be done about it.
1551 *convert = CONVERT_R32F;
1552 *format = GL_RGB;
1553 *internal = GL_RGB32F_ARB;
1554 *type = GL_FLOAT;
1555 *target_bpp = 12;
1556 break;
1558 case WINED3DFMT_R16F:
1559 /* Similar to R32F */
1560 *convert = CONVERT_R16F;
1561 *format = GL_RGB;
1562 *internal = GL_RGB16F_ARB;
1563 *type = GL_HALF_FLOAT_ARB;
1564 *target_bpp = 6;
1565 break;
1567 case WINED3DFMT_G16R16:
1568 *convert = CONVERT_G16R16;
1569 *format = GL_RGB;
1570 *internal = GL_RGB16_EXT;
1571 *type = GL_UNSIGNED_SHORT;
1572 *target_bpp = 6;
1573 break;
1575 default:
1576 break;
1579 return WINED3D_OK;
1582 HRESULT d3dfmt_convert_surface(BYTE *src, BYTE *dst, UINT pitch, UINT width, UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *This) {
1583 BYTE *source, *dest;
1584 TRACE("(%p)->(%p),(%d,%d,%d,%d,%p)\n", src, dst, pitch, height, outpitch, convert,This);
1586 switch (convert) {
1587 case NO_CONVERSION:
1589 memcpy(dst, src, pitch * height);
1590 break;
1592 case CONVERT_PALETTED:
1593 case CONVERT_PALETTED_CK:
1595 IWineD3DPaletteImpl* pal = This->palette;
1596 BYTE table[256][4];
1597 unsigned int x, y;
1599 if( pal == NULL) {
1600 /* TODO: If we are a sublevel, try to get the palette from level 0 */
1603 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
1605 for (y = 0; y < height; y++)
1607 source = src + pitch * y;
1608 dest = dst + outpitch * y;
1609 /* This is an 1 bpp format, using the width here is fine */
1610 for (x = 0; x < width; x++) {
1611 BYTE color = *source++;
1612 *dest++ = table[color][0];
1613 *dest++ = table[color][1];
1614 *dest++ = table[color][2];
1615 *dest++ = table[color][3];
1619 break;
1621 case CONVERT_CK_565:
1623 /* Converting the 565 format in 5551 packed to emulate color-keying.
1625 Note : in all these conversion, it would be best to average the averaging
1626 pixels to get the color of the pixel that will be color-keyed to
1627 prevent 'color bleeding'. This will be done later on if ever it is
1628 too visible.
1630 Note2: Nvidia documents say that their driver does not support alpha + color keying
1631 on the same surface and disables color keying in such a case
1633 unsigned int x, y;
1634 WORD *Source;
1635 WORD *Dest;
1637 TRACE("Color keyed 565\n");
1639 for (y = 0; y < height; y++) {
1640 Source = (WORD *) (src + y * pitch);
1641 Dest = (WORD *) (dst + y * outpitch);
1642 for (x = 0; x < width; x++ ) {
1643 WORD color = *Source++;
1644 *Dest = ((color & 0xFFC0) | ((color & 0x1F) << 1));
1645 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1646 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1647 *Dest |= 0x0001;
1649 Dest++;
1653 break;
1655 case CONVERT_CK_5551:
1657 /* Converting X1R5G5B5 format to R5G5B5A1 to emulate color-keying. */
1658 unsigned int x, y;
1659 WORD *Source;
1660 WORD *Dest;
1661 TRACE("Color keyed 5551\n");
1662 for (y = 0; y < height; y++) {
1663 Source = (WORD *) (src + y * pitch);
1664 Dest = (WORD *) (dst + y * outpitch);
1665 for (x = 0; x < width; x++ ) {
1666 WORD color = *Source++;
1667 *Dest = color;
1668 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1669 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1670 *Dest |= (1 << 15);
1672 else {
1673 *Dest &= ~(1 << 15);
1675 Dest++;
1679 break;
1681 case CONVERT_V8U8:
1683 unsigned int x, y;
1684 short *Source;
1685 unsigned char *Dest;
1686 for(y = 0; y < height; y++) {
1687 Source = (short *) (src + y * pitch);
1688 Dest = (unsigned char *) (dst + y * outpitch);
1689 for (x = 0; x < width; x++ ) {
1690 long color = (*Source++);
1691 /* B */ Dest[0] = 0xff;
1692 /* G */ Dest[1] = (color >> 8) + 128; /* V */
1693 /* R */ Dest[2] = (color) + 128; /* U */
1694 Dest += 3;
1697 break;
1700 case CONVERT_V16U16:
1702 unsigned int x, y;
1703 DWORD *Source;
1704 unsigned short *Dest;
1705 for(y = 0; y < height; y++) {
1706 Source = (DWORD *) (src + y * pitch);
1707 Dest = (unsigned short *) (dst + y * outpitch);
1708 for (x = 0; x < width; x++ ) {
1709 DWORD color = (*Source++);
1710 /* B */ Dest[0] = 0xffff;
1711 /* G */ Dest[1] = (color >> 16) + 32768; /* V */
1712 /* R */ Dest[2] = (color ) + 32768; /* U */
1713 Dest += 3;
1716 break;
1719 case CONVERT_Q8W8V8U8:
1721 unsigned int x, y;
1722 DWORD *Source;
1723 unsigned char *Dest;
1724 for(y = 0; y < height; y++) {
1725 Source = (DWORD *) (src + y * pitch);
1726 Dest = (unsigned char *) (dst + y * outpitch);
1727 for (x = 0; x < width; x++ ) {
1728 long color = (*Source++);
1729 /* B */ Dest[0] = ((color >> 16) & 0xff) + 128; /* W */
1730 /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
1731 /* R */ Dest[2] = (color & 0xff) + 128; /* U */
1732 /* A */ Dest[3] = ((color >> 24) & 0xff) + 128; /* Q */
1733 Dest += 4;
1736 break;
1739 case CONVERT_L6V5U5:
1741 unsigned int x, y;
1742 WORD *Source;
1743 unsigned char *Dest;
1745 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1746 /* This makes the gl surface bigger(24 bit instead of 16), but it works with
1747 * fixed function and shaders without further conversion once the surface is
1748 * loaded
1750 for(y = 0; y < height; y++) {
1751 Source = (WORD *) (src + y * pitch);
1752 Dest = (unsigned char *) (dst + y * outpitch);
1753 for (x = 0; x < width; x++ ) {
1754 short color = (*Source++);
1755 unsigned char l = ((color >> 10) & 0xfc);
1756 char v = ((color >> 5) & 0x3e);
1757 char u = ((color ) & 0x1f);
1759 /* 8 bits destination, 6 bits source, 8th bit is the sign. gl ignores the sign
1760 * and doubles the positive range. Thus shift left only once, gl does the 2nd
1761 * shift. GL reads a signed value and converts it into an unsigned value.
1763 /* M */ Dest[2] = l << 1;
1765 /* Those are read as signed, but kept signed. Just left-shift 3 times to scale
1766 * from 5 bit values to 8 bit values.
1768 /* V */ Dest[1] = v << 3;
1769 /* U */ Dest[0] = u << 3;
1770 Dest += 3;
1773 } else {
1774 for(y = 0; y < height; y++) {
1775 unsigned short *Dest_s = (unsigned short *) (dst + y * outpitch);
1776 Source = (WORD *) (src + y * pitch);
1777 for (x = 0; x < width; x++ ) {
1778 short color = (*Source++);
1779 unsigned char l = ((color >> 10) & 0xfc);
1780 short v = ((color >> 5) & 0x3e);
1781 short u = ((color ) & 0x1f);
1782 short v_conv = v + 16;
1783 short u_conv = u + 16;
1785 *Dest_s = ((v_conv << 11) & 0xf800) | ((l << 5) & 0x7e0) | (u_conv & 0x1f);
1786 Dest_s += 1;
1790 break;
1793 case CONVERT_X8L8V8U8:
1795 unsigned int x, y;
1796 DWORD *Source;
1797 unsigned char *Dest;
1799 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1800 /* This implementation works with the fixed function pipeline and shaders
1801 * without further modification after converting the surface.
1803 for(y = 0; y < height; y++) {
1804 Source = (DWORD *) (src + y * pitch);
1805 Dest = (unsigned char *) (dst + y * outpitch);
1806 for (x = 0; x < width; x++ ) {
1807 long color = (*Source++);
1808 /* L */ Dest[2] = ((color >> 16) & 0xff); /* L */
1809 /* V */ Dest[1] = ((color >> 8 ) & 0xff); /* V */
1810 /* U */ Dest[0] = (color & 0xff); /* U */
1811 /* I */ Dest[3] = 255; /* X */
1812 Dest += 4;
1815 } else {
1816 /* Doesn't work correctly with the fixed function pipeline, but can work in
1817 * shaders if the shader is adjusted. (There's no use for this format in gl's
1818 * standard fixed function pipeline anyway).
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 /* B */ Dest[0] = ((color >> 16) & 0xff); /* L */
1826 /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
1827 /* R */ Dest[2] = (color & 0xff) + 128; /* U */
1828 Dest += 4;
1832 break;
1835 case CONVERT_A4L4:
1837 unsigned int x, y;
1838 unsigned char *Source;
1839 unsigned char *Dest;
1840 for(y = 0; y < height; y++) {
1841 Source = (unsigned char *) (src + y * pitch);
1842 Dest = (unsigned char *) (dst + y * outpitch);
1843 for (x = 0; x < width; x++ ) {
1844 unsigned char color = (*Source++);
1845 /* A */ Dest[1] = (color & 0xf0) << 0;
1846 /* L */ Dest[0] = (color & 0x0f) << 4;
1847 Dest += 2;
1850 break;
1853 case CONVERT_R32F:
1855 unsigned int x, y;
1856 float *Source;
1857 float *Dest;
1858 for(y = 0; y < height; y++) {
1859 Source = (float *) (src + y * pitch);
1860 Dest = (float *) (dst + y * outpitch);
1861 for (x = 0; x < width; x++ ) {
1862 float color = (*Source++);
1863 Dest[0] = color;
1864 Dest[1] = 1.0;
1865 Dest[2] = 1.0;
1866 Dest += 3;
1869 break;
1872 case CONVERT_R16F:
1874 unsigned int x, y;
1875 WORD *Source;
1876 WORD *Dest;
1877 WORD one = 0x3c00;
1878 for(y = 0; y < height; y++) {
1879 Source = (WORD *) (src + y * pitch);
1880 Dest = (WORD *) (dst + y * outpitch);
1881 for (x = 0; x < width; x++ ) {
1882 WORD color = (*Source++);
1883 Dest[0] = color;
1884 Dest[1] = one;
1885 Dest[2] = one;
1886 Dest += 3;
1889 break;
1892 case CONVERT_G16R16:
1894 unsigned int x, y;
1895 WORD *Source;
1896 WORD *Dest;
1898 for(y = 0; y < height; y++) {
1899 Source = (WORD *) (src + y * pitch);
1900 Dest = (WORD *) (dst + y * outpitch);
1901 for (x = 0; x < width; x++ ) {
1902 WORD green = (*Source++);
1903 WORD red = (*Source++);
1904 Dest[0] = green;
1905 Dest[1] = red;
1906 Dest[2] = 0xffff;
1907 Dest += 3;
1910 break;
1913 default:
1914 ERR("Unsupported conversation type %d\n", convert);
1916 return WINED3D_OK;
1919 static void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey) {
1920 IWineD3DPaletteImpl* pal = This->palette;
1921 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1922 BOOL index_in_alpha = FALSE;
1923 int i;
1925 /* Old games like StarCraft, C&C, Red Alert and others use P8 render targets.
1926 * Reading back the RGB output each lockrect (each frame as they lock the whole screen)
1927 * is slow. Further RGB->P8 conversion is not possible because palettes can have
1928 * duplicate entries. Store the color key in the unused alpha component to speed the
1929 * download up and to make conversion unneeded. */
1930 if (device->render_targets && device->render_targets[0]) {
1931 IWineD3DSurfaceImpl* render_target = (IWineD3DSurfaceImpl*)device->render_targets[0];
1933 if((render_target->resource.usage & WINED3DUSAGE_RENDERTARGET) && (render_target->resource.format == WINED3DFMT_P8))
1934 index_in_alpha = TRUE;
1937 if (pal == NULL) {
1938 /* Still no palette? Use the device's palette */
1939 /* Get the surface's palette */
1940 for (i = 0; i < 256; i++) {
1941 table[i][0] = device->palettes[device->currentPalette][i].peRed;
1942 table[i][1] = device->palettes[device->currentPalette][i].peGreen;
1943 table[i][2] = device->palettes[device->currentPalette][i].peBlue;
1945 if(index_in_alpha) {
1946 table[i][3] = i;
1947 } else if (colorkey &&
1948 (i >= This->SrcBltCKey.dwColorSpaceLowValue) &&
1949 (i <= This->SrcBltCKey.dwColorSpaceHighValue)) {
1950 /* We should maybe here put a more 'neutral' color than the standard bright purple
1951 one often used by application to prevent the nice purple borders when bi-linear
1952 filtering is on */
1953 table[i][3] = 0x00;
1954 } else {
1955 table[i][3] = 0xFF;
1958 } else {
1959 TRACE("Using surface palette %p\n", pal);
1960 /* Get the surface's palette */
1961 for (i = 0; i < 256; i++) {
1962 table[i][0] = pal->palents[i].peRed;
1963 table[i][1] = pal->palents[i].peGreen;
1964 table[i][2] = pal->palents[i].peBlue;
1966 if(index_in_alpha) {
1967 table[i][3] = i;
1969 else if (colorkey &&
1970 (i >= This->SrcBltCKey.dwColorSpaceLowValue) &&
1971 (i <= This->SrcBltCKey.dwColorSpaceHighValue)) {
1972 /* We should maybe here put a more 'neutral' color than the standard bright purple
1973 one often used by application to prevent the nice purple borders when bi-linear
1974 filtering is on */
1975 table[i][3] = 0x00;
1976 } else if(pal->Flags & WINEDDPCAPS_ALPHA) {
1977 table[i][3] = pal->palents[i].peFlags;
1978 } else {
1979 table[i][3] = 0xFF;
1985 const char *fragment_palette_conversion =
1986 "!!ARBfp1.0\n"
1987 "TEMP index;\n"
1988 "PARAM constants = { 0.996, 0.00195, 0, 0 };\n" /* { 255/256, 0.5/255*255/256, 0, 0 } */
1989 "TEX index.x, fragment.texcoord[0], texture[0], 2D;\n" /* store the red-component of the current pixel */
1990 "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 */
1991 "TEX result.color, index, texture[1], 1D;\n" /* use the red-component as a index in the palette to get the final color */
1992 "END";
1994 /* This function is used in case of 8bit paletted textures to upload the palette.
1995 It supports GL_EXT_paletted_texture and GL_ARB_fragment_program, support for other
1996 extensions like ATI_fragment_shaders is possible.
1998 static void d3dfmt_p8_upload_palette(IWineD3DSurface *iface, CONVERT_TYPES convert) {
1999 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2000 BYTE table[256][4];
2001 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2003 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
2005 /* Try to use the paletted texture extension */
2006 if(GL_SUPPORT(EXT_PALETTED_TEXTURE))
2008 TRACE("Using GL_EXT_PALETTED_TEXTURE for 8-bit paletted texture support\n");
2009 GL_EXTCALL(glColorTableEXT(This->glDescription.target,GL_RGBA,256,GL_RGBA,GL_UNSIGNED_BYTE, table));
2011 else
2013 /* Let a fragment shader do the color conversion by uploading the palette to a 1D texture.
2014 * The 8bit pixel data will be used as an index in this palette texture to retrieve the final color. */
2015 TRACE("Using fragment shaders for emulating 8-bit paletted texture support\n");
2017 /* Create the fragment program if we don't have it */
2018 if(!device->paletteConversionShader)
2020 glEnable(GL_FRAGMENT_PROGRAM_ARB);
2021 GL_EXTCALL(glGenProgramsARB(1, &device->paletteConversionShader));
2022 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, device->paletteConversionShader));
2023 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(fragment_palette_conversion), (const GLbyte *)fragment_palette_conversion));
2024 glDisable(GL_FRAGMENT_PROGRAM_ARB);
2027 glEnable(GL_FRAGMENT_PROGRAM_ARB);
2028 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, device->paletteConversionShader));
2030 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE1));
2031 glEnable(GL_TEXTURE_1D);
2032 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2034 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2035 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); /* Make sure we have discrete color levels. */
2036 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2037 glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, table); /* Upload the palette */
2039 /* Switch back to unit 0 in which the 2D texture will be stored. */
2040 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0));
2042 /* Rebind the texture because it isn't bound anymore */
2043 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2047 static BOOL palette9_changed(IWineD3DSurfaceImpl *This) {
2048 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2050 if(This->palette || (This->resource.format != WINED3DFMT_P8 && This->resource.format != WINED3DFMT_A8P8)) {
2051 /* If a ddraw-style palette is attached assume no d3d9 palette change.
2052 * Also the palette isn't interesting if the surface format isn't P8 or A8P8
2054 return FALSE;
2057 if(This->palette9) {
2058 if(memcmp(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256) == 0) {
2059 return FALSE;
2061 } else {
2062 This->palette9 = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
2064 memcpy(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256);
2065 return TRUE;
2068 static inline void clear_unused_channels(IWineD3DSurfaceImpl *This) {
2069 GLboolean oldwrite[4];
2071 /* Some formats have only some color channels, and the others are 1.0.
2072 * since our rendering renders to all channels, and those pixel formats
2073 * are emulated by using a full texture with the other channels set to 1.0
2074 * manually, clear the unused channels.
2076 * This could be done with hacking colorwriteenable to mask the colors,
2077 * but before drawing the buffer would have to be cleared too, so there's
2078 * no gain in that
2080 switch(This->resource.format) {
2081 case WINED3DFMT_R16F:
2082 case WINED3DFMT_R32F:
2083 TRACE("R16F or R32F format, clearing green, blue and alpha to 1.0\n");
2084 /* Do not activate a context, the correct drawable is active already
2085 * though just the read buffer is set, make sure to have the correct draw
2086 * buffer too
2088 glDrawBuffer(This->resource.wineD3DDevice->offscreenBuffer);
2089 glDisable(GL_SCISSOR_TEST);
2090 glGetBooleanv(GL_COLOR_WRITEMASK, oldwrite);
2091 glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_TRUE);
2092 glClearColor(0.0, 1.0, 1.0, 1.0);
2093 glClear(GL_COLOR_BUFFER_BIT);
2094 glColorMask(oldwrite[0], oldwrite[1], oldwrite[2], oldwrite[3]);
2095 if(!This->resource.wineD3DDevice->render_offscreen) glDrawBuffer(GL_BACK);
2096 checkGLcall("Unused channel clear\n");
2097 break;
2099 default: break;
2103 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadTexture(IWineD3DSurface *iface, BOOL srgb_mode) {
2104 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2106 if (!(This->Flags & SFLAG_INTEXTURE)) {
2107 TRACE("Reloading because surface is dirty\n");
2108 } else if(/* Reload: gl texture has ck, now no ckey is set OR */
2109 ((This->Flags & SFLAG_GLCKEY) && (!(This->CKeyFlags & WINEDDSD_CKSRCBLT))) ||
2110 /* Reload: vice versa OR */
2111 ((!(This->Flags & SFLAG_GLCKEY)) && (This->CKeyFlags & WINEDDSD_CKSRCBLT)) ||
2112 /* Also reload: Color key is active AND the color key has changed */
2113 ((This->CKeyFlags & WINEDDSD_CKSRCBLT) && (
2114 (This->glCKey.dwColorSpaceLowValue != This->SrcBltCKey.dwColorSpaceLowValue) ||
2115 (This->glCKey.dwColorSpaceHighValue != This->SrcBltCKey.dwColorSpaceHighValue)))) {
2116 TRACE("Reloading because of color keying\n");
2117 /* To perform the color key conversion we need a sysmem copy of
2118 * the surface. Make sure we have it
2120 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
2121 } else if(palette9_changed(This)) {
2122 TRACE("Reloading surface because the d3d8/9 palette was changed\n");
2123 /* TODO: This is not necessarily needed with hw palettized texture support */
2124 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
2125 } else {
2126 TRACE("surface is already in texture\n");
2127 return WINED3D_OK;
2130 /* Resources are placed in system RAM and do not need to be recreated when a device is lost.
2131 * These resources are not bound by device size or format restrictions. Because of this,
2132 * these resources cannot be accessed by the Direct3D device nor set as textures or render targets.
2133 * However, these resources can always be created, locked, and copied.
2135 if (This->resource.pool == WINED3DPOOL_SCRATCH )
2137 FIXME("(%p) Operation not supported for scratch textures\n",This);
2138 return WINED3DERR_INVALIDCALL;
2141 This->srgb = srgb_mode;
2142 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* no partial locking for textures yet */);
2144 #if 0
2146 static unsigned int gen = 0;
2147 char buffer[4096];
2148 ++gen;
2149 if ((gen % 10) == 0) {
2150 snprintf(buffer, sizeof(buffer), "/tmp/surface%p_type%u_level%u_%u.ppm", This, This->glDescription.target, This->glDescription.level, gen);
2151 IWineD3DSurfaceImpl_SaveSnapshot(iface, buffer);
2154 * debugging crash code
2155 if (gen == 250) {
2156 void** test = NULL;
2157 *test = 0;
2161 #endif
2163 if (!(This->Flags & SFLAG_DONOTFREE)) {
2164 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
2165 This->resource.allocatedMemory = NULL;
2166 This->resource.heapMemory = NULL;
2167 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, FALSE);
2170 return WINED3D_OK;
2173 static void WINAPI IWineD3DSurfaceImpl_BindTexture(IWineD3DSurface *iface) {
2174 /* TODO: check for locks */
2175 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2176 IWineD3DBaseTexture *baseTexture = NULL;
2177 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2179 TRACE("(%p)Checking to see if the container is a base texture\n", This);
2180 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
2181 TRACE("Passing to container\n");
2182 IWineD3DBaseTexture_BindTexture(baseTexture);
2183 IWineD3DBaseTexture_Release(baseTexture);
2184 } else {
2185 TRACE("(%p) : Binding surface\n", This);
2187 if(!device->isInDraw) {
2188 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
2190 ENTER_GL();
2191 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2192 LEAVE_GL();
2194 return;
2197 #include <errno.h>
2198 #include <stdio.h>
2199 HRESULT WINAPI IWineD3DSurfaceImpl_SaveSnapshot(IWineD3DSurface *iface, const char* filename) {
2200 FILE* f = NULL;
2201 UINT i, y;
2202 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2203 char *allocatedMemory;
2204 char *textureRow;
2205 IWineD3DSwapChain *swapChain = NULL;
2206 int width, height;
2207 GLuint tmpTexture = 0;
2208 DWORD color;
2209 /*FIXME:
2210 Textures may not be stored in ->allocatedgMemory and a GlTexture
2211 so we should lock the surface before saving a snapshot, or at least check that
2213 /* TODO: Compressed texture images can be obtained from the GL in uncompressed form
2214 by calling GetTexImage and in compressed form by calling
2215 GetCompressedTexImageARB. Queried compressed images can be saved and
2216 later reused by calling CompressedTexImage[123]DARB. Pre-compressed
2217 texture images do not need to be processed by the GL and should
2218 significantly improve texture loading performance relative to uncompressed
2219 images. */
2221 /* Setup the width and height to be the internal texture width and height. */
2222 width = This->pow2Width;
2223 height = This->pow2Height;
2224 /* check to see if we're a 'virtual' texture, e.g. we're not a pbuffer of texture, we're a back buffer*/
2225 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapChain);
2227 if (This->Flags & SFLAG_INDRAWABLE && !(This->Flags & SFLAG_INTEXTURE)) {
2228 /* if were not a real texture then read the back buffer into a real texture */
2229 /* we don't want to interfere with the back buffer so read the data into a temporary
2230 * texture and then save the data out of the temporary texture
2232 GLint prevRead;
2233 ENTER_GL();
2234 TRACE("(%p) Reading render target into texture\n", This);
2235 glEnable(GL_TEXTURE_2D);
2237 glGenTextures(1, &tmpTexture);
2238 glBindTexture(GL_TEXTURE_2D, tmpTexture);
2240 glTexImage2D(GL_TEXTURE_2D,
2242 GL_RGBA,
2243 width,
2244 height,
2245 0/*border*/,
2246 GL_RGBA,
2247 GL_UNSIGNED_INT_8_8_8_8_REV,
2248 NULL);
2250 glGetIntegerv(GL_READ_BUFFER, &prevRead);
2251 vcheckGLcall("glGetIntegerv");
2252 glReadBuffer(swapChain ? GL_BACK : This->resource.wineD3DDevice->offscreenBuffer);
2253 vcheckGLcall("glReadBuffer");
2254 glCopyTexImage2D(GL_TEXTURE_2D,
2256 GL_RGBA,
2259 width,
2260 height,
2263 checkGLcall("glCopyTexImage2D");
2264 glReadBuffer(prevRead);
2265 LEAVE_GL();
2267 } else { /* bind the real texture, and make sure it up to date */
2268 IWineD3DSurface_PreLoad(iface);
2270 allocatedMemory = HeapAlloc(GetProcessHeap(), 0, width * height * 4);
2271 ENTER_GL();
2272 FIXME("Saving texture level %d width %d height %d\n", This->glDescription.level, width, height);
2273 glGetTexImage(GL_TEXTURE_2D,
2274 This->glDescription.level,
2275 GL_RGBA,
2276 GL_UNSIGNED_INT_8_8_8_8_REV,
2277 allocatedMemory);
2278 checkGLcall("glTexImage2D");
2279 if (tmpTexture) {
2280 glBindTexture(GL_TEXTURE_2D, 0);
2281 glDeleteTextures(1, &tmpTexture);
2283 LEAVE_GL();
2285 f = fopen(filename, "w+");
2286 if (NULL == f) {
2287 ERR("opening of %s failed with: %s\n", filename, strerror(errno));
2288 return WINED3DERR_INVALIDCALL;
2290 /* Save the data out to a TGA file because 1: it's an easy raw format, 2: it supports an alpha channel */
2291 TRACE("(%p) opened %s with format %s\n", This, filename, debug_d3dformat(This->resource.format));
2292 /* TGA header */
2293 fputc(0,f);
2294 fputc(0,f);
2295 fputc(2,f);
2296 fputc(0,f);
2297 fputc(0,f);
2298 fputc(0,f);
2299 fputc(0,f);
2300 fputc(0,f);
2301 fputc(0,f);
2302 fputc(0,f);
2303 fputc(0,f);
2304 fputc(0,f);
2305 /* short width*/
2306 fwrite(&width,2,1,f);
2307 /* short height */
2308 fwrite(&height,2,1,f);
2309 /* format rgba */
2310 fputc(0x20,f);
2311 fputc(0x28,f);
2312 /* raw data */
2313 /* 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 */
2314 if(swapChain)
2315 textureRow = allocatedMemory + (width * (height - 1) *4);
2316 else
2317 textureRow = allocatedMemory;
2318 for (y = 0 ; y < height; y++) {
2319 for (i = 0; i < width; i++) {
2320 color = *((DWORD*)textureRow);
2321 fputc((color >> 16) & 0xFF, f); /* B */
2322 fputc((color >> 8) & 0xFF, f); /* G */
2323 fputc((color >> 0) & 0xFF, f); /* R */
2324 fputc((color >> 24) & 0xFF, f); /* A */
2325 textureRow += 4;
2327 /* take two rows of the pointer to the texture memory */
2328 if(swapChain)
2329 (textureRow-= width << 3);
2332 TRACE("Closing file\n");
2333 fclose(f);
2335 if(swapChain) {
2336 IWineD3DSwapChain_Release(swapChain);
2338 HeapFree(GetProcessHeap(), 0, allocatedMemory);
2339 return WINED3D_OK;
2343 * Slightly inefficient way to handle multiple dirty rects but it works :)
2345 extern HRESULT WINAPI IWineD3DSurfaceImpl_AddDirtyRect(IWineD3DSurface *iface, CONST RECT* pDirtyRect) {
2346 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2347 IWineD3DBaseTexture *baseTexture = NULL;
2349 if (!(This->Flags & SFLAG_INSYSMEM) && (This->Flags & SFLAG_INTEXTURE))
2350 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL /* no partial locking for textures yet */);
2352 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2353 if (NULL != pDirtyRect) {
2354 This->dirtyRect.left = min(This->dirtyRect.left, pDirtyRect->left);
2355 This->dirtyRect.top = min(This->dirtyRect.top, pDirtyRect->top);
2356 This->dirtyRect.right = max(This->dirtyRect.right, pDirtyRect->right);
2357 This->dirtyRect.bottom = max(This->dirtyRect.bottom, pDirtyRect->bottom);
2358 } else {
2359 This->dirtyRect.left = 0;
2360 This->dirtyRect.top = 0;
2361 This->dirtyRect.right = This->currentDesc.Width;
2362 This->dirtyRect.bottom = This->currentDesc.Height;
2364 TRACE("(%p) : Dirty: yes, Rect:(%d,%d,%d,%d)\n", This, This->dirtyRect.left,
2365 This->dirtyRect.top, This->dirtyRect.right, This->dirtyRect.bottom);
2366 /* if the container is a basetexture then mark it dirty. */
2367 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
2368 TRACE("Passing to container\n");
2369 IWineD3DBaseTexture_SetDirty(baseTexture, TRUE);
2370 IWineD3DBaseTexture_Release(baseTexture);
2372 return WINED3D_OK;
2375 HRESULT WINAPI IWineD3DSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format) {
2376 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2377 HRESULT hr;
2378 const GlPixelFormatDesc *glDesc;
2379 getFormatDescEntry(format, &GLINFO_LOCATION, &glDesc);
2381 TRACE("(%p) : Calling base function first\n", This);
2382 hr = IWineD3DBaseSurfaceImpl_SetFormat(iface, format);
2383 if(SUCCEEDED(hr)) {
2384 /* Setup some glformat defaults */
2385 This->glDescription.glFormat = glDesc->glFormat;
2386 This->glDescription.glFormatInternal = glDesc->glInternal;
2387 This->glDescription.glType = glDesc->glType;
2389 This->Flags &= ~SFLAG_ALLOCATED;
2390 TRACE("(%p) : glFormat %d, glFotmatInternal %d, glType %d\n", This,
2391 This->glDescription.glFormat, This->glDescription.glFormatInternal, This->glDescription.glType);
2393 return hr;
2396 HRESULT WINAPI IWineD3DSurfaceImpl_SetMem(IWineD3DSurface *iface, void *Mem) {
2397 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
2399 if(This->Flags & (SFLAG_LOCKED | SFLAG_DCINUSE)) {
2400 WARN("Surface is locked or the HDC is in use\n");
2401 return WINED3DERR_INVALIDCALL;
2404 if(Mem && Mem != This->resource.allocatedMemory) {
2405 void *release = NULL;
2407 /* Do I have to copy the old surface content? */
2408 if(This->Flags & SFLAG_DIBSECTION) {
2409 /* Release the DC. No need to hold the critical section for the update
2410 * Thread because this thread runs only on front buffers, but this method
2411 * fails for render targets in the check above.
2413 SelectObject(This->hDC, This->dib.holdbitmap);
2414 DeleteDC(This->hDC);
2415 /* Release the DIB section */
2416 DeleteObject(This->dib.DIBsection);
2417 This->dib.bitmap_data = NULL;
2418 This->resource.allocatedMemory = NULL;
2419 This->hDC = NULL;
2420 This->Flags &= ~SFLAG_DIBSECTION;
2421 } else if(!(This->Flags & SFLAG_USERPTR)) {
2422 release = This->resource.heapMemory;
2423 This->resource.heapMemory = NULL;
2425 This->resource.allocatedMemory = Mem;
2426 This->Flags |= SFLAG_USERPTR | SFLAG_INSYSMEM;
2428 /* Now the surface memory is most up do date. Invalidate drawable and texture */
2429 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2431 /* For client textures opengl has to be notified */
2432 if(This->Flags & SFLAG_CLIENT) {
2433 This->Flags &= ~SFLAG_ALLOCATED;
2434 IWineD3DSurface_PreLoad(iface);
2435 /* And hope that the app behaves correctly and did not free the old surface memory before setting a new pointer */
2438 /* Now free the old memory if any */
2439 HeapFree(GetProcessHeap(), 0, release);
2440 } else if(This->Flags & SFLAG_USERPTR) {
2441 /* Lockrect and GetDC will re-create the dib section and allocated memory */
2442 This->resource.allocatedMemory = NULL;
2443 /* HeapMemory should be NULL already */
2444 if(This->resource.heapMemory != NULL) ERR("User pointer surface has heap memory allocated\n");
2445 This->Flags &= ~SFLAG_USERPTR;
2447 if(This->Flags & SFLAG_CLIENT) {
2448 This->Flags &= ~SFLAG_ALLOCATED;
2449 /* This respecifies an empty texture and opengl knows that the old memory is gone */
2450 IWineD3DSurface_PreLoad(iface);
2453 return WINED3D_OK;
2456 static HRESULT WINAPI IWineD3DSurfaceImpl_Flip(IWineD3DSurface *iface, IWineD3DSurface *override, DWORD Flags) {
2457 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2458 IWineD3DSwapChainImpl *swapchain = NULL;
2459 HRESULT hr;
2460 TRACE("(%p)->(%p,%x)\n", This, override, Flags);
2462 /* Flipping is only supported on RenderTargets */
2463 if( !(This->resource.usage & WINED3DUSAGE_RENDERTARGET) ) return WINEDDERR_NOTFLIPPABLE;
2465 if(override) {
2466 /* DDraw sets this for the X11 surfaces, so don't confuse the user
2467 * FIXME("(%p) Target override is not supported by now\n", This);
2468 * Additionally, it isn't really possible to support triple-buffering
2469 * properly on opengl at all
2473 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **) &swapchain);
2474 if(!swapchain) {
2475 ERR("Flipped surface is not on a swapchain\n");
2476 return WINEDDERR_NOTFLIPPABLE;
2479 /* Just overwrite the swapchain presentation interval. This is ok because only ddraw apps can call Flip,
2480 * and only d3d8 and d3d9 apps specify the presentation interval
2482 if((Flags & (WINEDDFLIP_NOVSYNC | WINEDDFLIP_INTERVAL2 | WINEDDFLIP_INTERVAL3 | WINEDDFLIP_INTERVAL4)) == 0) {
2483 /* Most common case first to avoid wasting time on all the other cases */
2484 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_ONE;
2485 } else if(Flags & WINEDDFLIP_NOVSYNC) {
2486 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
2487 } else if(Flags & WINEDDFLIP_INTERVAL2) {
2488 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_TWO;
2489 } else if(Flags & WINEDDFLIP_INTERVAL3) {
2490 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_THREE;
2491 } else {
2492 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_FOUR;
2495 /* Flipping a OpenGL surface -> Use WineD3DDevice::Present */
2496 hr = IWineD3DSwapChain_Present((IWineD3DSwapChain *) swapchain, NULL, NULL, 0, NULL, 0);
2497 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
2498 return hr;
2501 /* Does a direct frame buffer -> texture copy. Stretching is done
2502 * with single pixel copy calls
2504 static inline void fb_copy_to_texture_direct(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface, IWineD3DSwapChainImpl *swapchain, WINED3DRECT *srect, WINED3DRECT *drect, BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter) {
2505 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2506 float xrel, yrel;
2507 UINT row;
2508 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2511 ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
2512 ENTER_GL();
2513 IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
2515 /* TODO: Do we need GL_TEXTURE_2D enabled fpr copyteximage? */
2516 glEnable(This->glDescription.target);
2517 checkGLcall("glEnable(This->glDescription.target)");
2519 /* Bind the target texture */
2520 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2521 checkGLcall("glBindTexture");
2522 if(!swapchain) {
2523 glReadBuffer(myDevice->offscreenBuffer);
2524 } else {
2525 GLenum buffer = surface_get_gl_buffer(SrcSurface, (IWineD3DSwapChain *)swapchain);
2526 glReadBuffer(buffer);
2528 checkGLcall("glReadBuffer");
2530 xrel = (float) (srect->x2 - srect->x1) / (float) (drect->x2 - drect->x1);
2531 yrel = (float) (srect->y2 - srect->y1) / (float) (drect->y2 - drect->y1);
2533 if( (xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) {
2534 FIXME("Doing a pixel by pixel copy from the framebuffer to a texture, expect major performance issues\n");
2536 if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
2537 ERR("Texture filtering not supported in direct blit\n");
2539 } else if((Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) && ((yrel - 1.0 < -eps) || (yrel - 1.0 > eps))) {
2540 ERR("Texture filtering not supported in direct blit\n");
2543 if(upsidedown &&
2544 !((xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) &&
2545 !((yrel - 1.0 < -eps) || (yrel - 1.0 > eps))) {
2546 /* Upside down copy without stretching is nice, one glCopyTexSubImage call will do */
2548 glCopyTexSubImage2D(This->glDescription.target,
2549 This->glDescription.level,
2550 drect->x1, drect->y1, /* xoffset, yoffset */
2551 srect->x1, Src->currentDesc.Height - srect->y2,
2552 drect->x2 - drect->x1, drect->y2 - drect->y1);
2553 } else {
2554 UINT yoffset = Src->currentDesc.Height - srect->y1 + drect->y1 - 1;
2555 /* I have to process this row by row to swap the image,
2556 * otherwise it would be upside down, so stretching in y direction
2557 * doesn't cost extra time
2559 * However, stretching in x direction can be avoided if not necessary
2561 for(row = drect->y1; row < drect->y2; row++) {
2562 if( (xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) {
2563 /* Well, that stuff works, but it's very slow.
2564 * find a better way instead
2566 UINT col;
2568 for(col = drect->x1; col < drect->x2; col++) {
2569 glCopyTexSubImage2D(This->glDescription.target,
2570 This->glDescription.level,
2571 drect->x1 + col, row, /* xoffset, yoffset */
2572 srect->x1 + col * xrel, yoffset - (int) (row * yrel),
2573 1, 1);
2575 } else {
2576 glCopyTexSubImage2D(This->glDescription.target,
2577 This->glDescription.level,
2578 drect->x1, row, /* xoffset, yoffset */
2579 srect->x1, yoffset - (int) (row * yrel),
2580 drect->x2-drect->x1, 1);
2584 vcheckGLcall("glCopyTexSubImage2D");
2586 /* Leave the opengl state valid for blitting */
2587 glDisable(This->glDescription.target);
2588 checkGLcall("glDisable(This->glDescription.target)");
2590 LEAVE_GL();
2593 /* Uses the hardware to stretch and flip the image */
2594 static inline void fb_copy_to_texture_hwstretch(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface, IWineD3DSwapChainImpl *swapchain, WINED3DRECT *srect, WINED3DRECT *drect, BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter) {
2595 GLuint src, backup = 0;
2596 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2597 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2598 float left, right, top, bottom; /* Texture coordinates */
2599 UINT fbwidth = Src->currentDesc.Width;
2600 UINT fbheight = Src->currentDesc.Height;
2601 GLenum drawBuffer = GL_BACK;
2602 GLenum texture_target;
2604 TRACE("Using hwstretch blit\n");
2605 /* Activate the Proper context for reading from the source surface, set it up for blitting */
2606 ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
2607 ENTER_GL();
2609 IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
2611 /* Try to use an aux buffer for drawing the rectangle. This way it doesn't need restoring.
2612 * This way we don't have to wait for the 2nd readback to finish to leave this function.
2614 if(GL_LIMITS(aux_buffers) >= 2) {
2615 /* Got more than one aux buffer? Use the 2nd aux buffer */
2616 drawBuffer = GL_AUX1;
2617 } else if((swapchain || myDevice->offscreenBuffer == GL_BACK) && GL_LIMITS(aux_buffers) >= 1) {
2618 /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
2619 drawBuffer = GL_AUX0;
2622 if(!swapchain && wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2623 glGenTextures(1, &backup);
2624 checkGLcall("glGenTextures\n");
2625 glBindTexture(GL_TEXTURE_2D, backup);
2626 checkGLcall("glBindTexture(Src->glDescription.target, Src->glDescription.textureName)");
2627 texture_target = GL_TEXTURE_2D;
2628 } else {
2629 /* Backup the back buffer and copy the source buffer into a texture to draw an upside down stretched quad. If
2630 * we are reading from the back buffer, the backup can be used as source texture
2632 if(Src->glDescription.textureName == 0) {
2633 /* Get it a description */
2634 IWineD3DSurface_PreLoad(SrcSurface);
2636 texture_target = Src->glDescription.target;
2637 glBindTexture(texture_target, Src->glDescription.textureName);
2638 checkGLcall("glBindTexture(texture_target, Src->glDescription.textureName)");
2639 glEnable(texture_target);
2640 checkGLcall("glEnable(texture_target)");
2642 /* For now invalidate the texture copy of the back buffer. Drawable and sysmem copy are untouched */
2643 Src->Flags &= ~SFLAG_INTEXTURE;
2646 glReadBuffer(GL_BACK);
2647 checkGLcall("glReadBuffer(GL_BACK)");
2649 /* TODO: Only back up the part that will be overwritten */
2650 glCopyTexSubImage2D(texture_target, 0,
2651 0, 0 /* read offsets */,
2652 0, 0,
2653 fbwidth,
2654 fbheight);
2656 checkGLcall("glCopyTexSubImage2D");
2658 /* No issue with overriding these - the sampler is dirty due to blit usage */
2659 glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER,
2660 stateLookup[WINELOOKUP_MAGFILTER][Filter - minLookup[WINELOOKUP_MAGFILTER]]);
2661 checkGLcall("glTexParameteri");
2662 glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER,
2663 minMipLookup[Filter][WINED3DTEXF_NONE]);
2664 checkGLcall("glTexParameteri");
2666 if(!swapchain || (IWineD3DSurface *) Src == swapchain->backBuffer[0]) {
2667 src = backup ? backup : Src->glDescription.textureName;
2668 } else {
2669 glReadBuffer(GL_FRONT);
2670 checkGLcall("glReadBuffer(GL_FRONT)");
2672 glGenTextures(1, &src);
2673 checkGLcall("glGenTextures(1, &src)");
2674 glBindTexture(GL_TEXTURE_2D, src);
2675 checkGLcall("glBindTexture(GL_TEXTURE_2D, src)");
2677 /* TODO: Only copy the part that will be read. Use srect->x1, srect->y2 as origin, but with the width watch
2678 * out for power of 2 sizes
2680 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Src->pow2Width, Src->pow2Height, 0,
2681 GL_RGBA, GL_UNSIGNED_BYTE, NULL);
2682 checkGLcall("glTexImage2D");
2683 glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
2684 0, 0 /* read offsets */,
2685 0, 0,
2686 fbwidth,
2687 fbheight);
2689 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2690 checkGLcall("glTexParameteri");
2691 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2692 checkGLcall("glTexParameteri");
2694 glReadBuffer(GL_BACK);
2695 checkGLcall("glReadBuffer(GL_BACK)");
2697 if(texture_target != GL_TEXTURE_2D) {
2698 glDisable(texture_target);
2699 glEnable(GL_TEXTURE_2D);
2700 texture_target = GL_TEXTURE_2D;
2703 checkGLcall("glEnd and previous");
2705 left = (float) srect->x1 / (float) Src->pow2Width;
2706 right = (float) srect->x2 / (float) Src->pow2Width;
2708 if(upsidedown) {
2709 top = (float) (Src->currentDesc.Height - srect->y1) / (float) Src->pow2Height;
2710 bottom = (float) (Src->currentDesc.Height - srect->y2) / (float) Src->pow2Height;
2711 } else {
2712 top = (float) (Src->currentDesc.Height - srect->y2) / (float) Src->pow2Height;
2713 bottom = (float) (Src->currentDesc.Height - srect->y1) / (float) Src->pow2Height;
2716 /* draw the source texture stretched and upside down. The correct surface is bound already */
2717 glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
2718 glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
2720 glDrawBuffer(drawBuffer);
2721 glReadBuffer(drawBuffer);
2723 glBegin(GL_QUADS);
2724 /* bottom left */
2725 glTexCoord2f(left, bottom);
2726 glVertex2i(0, fbheight);
2728 /* top left */
2729 glTexCoord2f(left, top);
2730 glVertex2i(0, fbheight - drect->y2 - drect->y1);
2732 /* top right */
2733 glTexCoord2f(right, top);
2734 glVertex2i(drect->x2 - drect->x1, fbheight - drect->y2 - drect->y1);
2736 /* bottom right */
2737 glTexCoord2f(right, bottom);
2738 glVertex2i(drect->x2 - drect->x1, fbheight);
2739 glEnd();
2740 checkGLcall("glEnd and previous");
2742 if(texture_target != This->glDescription.target) {
2743 glDisable(texture_target);
2744 glEnable(This->glDescription.target);
2745 texture_target = This->glDescription.target;
2748 /* Now read the stretched and upside down image into the destination texture */
2749 glBindTexture(texture_target, This->glDescription.textureName);
2750 checkGLcall("glBindTexture");
2751 glCopyTexSubImage2D(texture_target,
2753 drect->x1, drect->y1, /* xoffset, yoffset */
2754 0, 0, /* We blitted the image to the origin */
2755 drect->x2 - drect->x1, drect->y2 - drect->y1);
2756 checkGLcall("glCopyTexSubImage2D");
2758 if(drawBuffer == GL_BACK) {
2759 /* Write the back buffer backup back */
2760 if(backup) {
2761 if(texture_target != GL_TEXTURE_2D) {
2762 glDisable(texture_target);
2763 glEnable(GL_TEXTURE_2D);
2764 texture_target = GL_TEXTURE_2D;
2766 glBindTexture(GL_TEXTURE_2D, backup);
2767 checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
2768 } else {
2769 if(texture_target != Src->glDescription.target) {
2770 glDisable(texture_target);
2771 glEnable(Src->glDescription.target);
2772 texture_target = Src->glDescription.target;
2774 glBindTexture(Src->glDescription.target, Src->glDescription.textureName);
2775 checkGLcall("glBindTexture(Src->glDescription.target, Src->glDescription.textureName)");
2778 glBegin(GL_QUADS);
2779 /* top left */
2780 glTexCoord2f(0.0, (float) fbheight / (float) Src->pow2Height);
2781 glVertex2i(0, 0);
2783 /* bottom left */
2784 glTexCoord2f(0.0, 0.0);
2785 glVertex2i(0, fbheight);
2787 /* bottom right */
2788 glTexCoord2f((float) fbwidth / (float) Src->pow2Width, 0.0);
2789 glVertex2i(fbwidth, Src->currentDesc.Height);
2791 /* top right */
2792 glTexCoord2f((float) fbwidth / (float) Src->pow2Width, (float) fbheight / (float) Src->pow2Height);
2793 glVertex2i(fbwidth, 0);
2794 glEnd();
2795 } else {
2796 /* Restore the old draw buffer */
2797 glDrawBuffer(GL_BACK);
2799 glDisable(texture_target);
2800 checkGLcall("glDisable(texture_target)");
2802 /* Cleanup */
2803 if(src != Src->glDescription.textureName && src != backup) {
2804 glDeleteTextures(1, &src);
2805 checkGLcall("glDeleteTextures(1, &src)");
2807 if(backup) {
2808 glDeleteTextures(1, &backup);
2809 checkGLcall("glDeleteTextures(1, &backup)");
2812 LEAVE_GL();
2815 /* Not called from the VTable */
2816 static HRESULT IWineD3DSurfaceImpl_BltOverride(IWineD3DSurfaceImpl *This, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
2817 WINED3DRECT rect;
2818 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2819 IWineD3DSwapChainImpl *srcSwapchain = NULL, *dstSwapchain = NULL;
2820 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2822 TRACE("(%p)->(%p,%p,%p,%08x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
2824 /* Get the swapchain. One of the surfaces has to be a primary surface */
2825 if(This->resource.pool == WINED3DPOOL_SYSTEMMEM) {
2826 WARN("Destination is in sysmem, rejecting gl blt\n");
2827 return WINED3DERR_INVALIDCALL;
2829 IWineD3DSurface_GetContainer( (IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&dstSwapchain);
2830 if(dstSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) dstSwapchain);
2831 if(Src) {
2832 if(Src->resource.pool == WINED3DPOOL_SYSTEMMEM) {
2833 WARN("Src is in sysmem, rejecting gl blt\n");
2834 return WINED3DERR_INVALIDCALL;
2836 IWineD3DSurface_GetContainer( (IWineD3DSurface *) Src, &IID_IWineD3DSwapChain, (void **)&srcSwapchain);
2837 if(srcSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) srcSwapchain);
2840 /* Early sort out of cases where no render target is used */
2841 if(!dstSwapchain && !srcSwapchain &&
2842 SrcSurface != myDevice->render_targets[0] && This != (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
2843 TRACE("No surface is render target, not using hardware blit. Src = %p, dst = %p\n", Src, This);
2844 return WINED3DERR_INVALIDCALL;
2847 /* No destination color keying supported */
2848 if(Flags & (WINEDDBLT_KEYDEST | WINEDDBLT_KEYDESTOVERRIDE)) {
2849 /* Can we support that with glBlendFunc if blitting to the frame buffer? */
2850 TRACE("Destination color key not supported in accelerated Blit, falling back to software\n");
2851 return WINED3DERR_INVALIDCALL;
2854 if (DestRect) {
2855 rect.x1 = DestRect->left;
2856 rect.y1 = DestRect->top;
2857 rect.x2 = DestRect->right;
2858 rect.y2 = DestRect->bottom;
2859 } else {
2860 rect.x1 = 0;
2861 rect.y1 = 0;
2862 rect.x2 = This->currentDesc.Width;
2863 rect.y2 = This->currentDesc.Height;
2866 /* The only case where both surfaces on a swapchain are supported is a back buffer -> front buffer blit on the same swapchain */
2867 if(dstSwapchain && dstSwapchain == srcSwapchain && dstSwapchain->backBuffer &&
2868 ((IWineD3DSurface *) This == dstSwapchain->frontBuffer) && SrcSurface == dstSwapchain->backBuffer[0]) {
2869 /* Half-life does a Blt from the back buffer to the front buffer,
2870 * Full surface size, no flags... Use present instead
2872 * This path will only be entered for d3d7 and ddraw apps, because d3d8/9 offer no way to blit TO the front buffer
2875 /* Check rects - IWineD3DDevice_Present doesn't handle them */
2876 while(1)
2878 RECT mySrcRect;
2879 TRACE("Looking if a Present can be done...\n");
2880 /* Source Rectangle must be full surface */
2881 if( SrcRect ) {
2882 if(SrcRect->left != 0 || SrcRect->top != 0 ||
2883 SrcRect->right != Src->currentDesc.Width || SrcRect->bottom != Src->currentDesc.Height) {
2884 TRACE("No, Source rectangle doesn't match\n");
2885 break;
2888 mySrcRect.left = 0;
2889 mySrcRect.top = 0;
2890 mySrcRect.right = Src->currentDesc.Width;
2891 mySrcRect.bottom = Src->currentDesc.Height;
2893 /* No stretching may occur */
2894 if(mySrcRect.right != rect.x2 - rect.x1 ||
2895 mySrcRect.bottom != rect.y2 - rect.y1) {
2896 TRACE("No, stretching is done\n");
2897 break;
2900 /* Destination must be full surface or match the clipping rectangle */
2901 if(This->clipper && ((IWineD3DClipperImpl *) This->clipper)->hWnd)
2903 RECT cliprect;
2904 POINT pos[2];
2905 GetClientRect(((IWineD3DClipperImpl *) This->clipper)->hWnd, &cliprect);
2906 pos[0].x = rect.x1;
2907 pos[0].y = rect.y1;
2908 pos[1].x = rect.x2;
2909 pos[1].y = rect.y2;
2910 MapWindowPoints(GetDesktopWindow(), ((IWineD3DClipperImpl *) This->clipper)->hWnd,
2911 pos, 2);
2913 if(pos[0].x != cliprect.left || pos[0].y != cliprect.top ||
2914 pos[1].x != cliprect.right || pos[1].y != cliprect.bottom)
2916 TRACE("No, dest rectangle doesn't match(clipper)\n");
2917 TRACE("Clip rect at (%d,%d)-(%d,%d)\n", cliprect.left, cliprect.top, cliprect.right, cliprect.bottom);
2918 TRACE("Blt dest: (%d,%d)-(%d,%d)\n", rect.x1, rect.y1, rect.x2, rect.y2);
2919 break;
2922 else
2924 if(rect.x1 != 0 || rect.y1 != 0 ||
2925 rect.x2 != This->currentDesc.Width || rect.y2 != This->currentDesc.Height) {
2926 TRACE("No, dest rectangle doesn't match(surface size)\n");
2927 break;
2931 TRACE("Yes\n");
2933 /* These flags are unimportant for the flag check, remove them */
2934 if((Flags & ~(WINEDDBLT_DONOTWAIT | WINEDDBLT_WAIT)) == 0) {
2935 WINED3DSWAPEFFECT orig_swap = dstSwapchain->presentParms.SwapEffect;
2937 /* The idea behind this is that a glReadPixels and a glDrawPixels call
2938 * take very long, while a flip is fast.
2939 * This applies to Half-Life, which does such Blts every time it finished
2940 * a frame, and to Prince of Persia 3D, which uses this to draw at least the main
2941 * menu. This is also used by all apps when they do windowed rendering
2943 * The problem is that flipping is not really the same as copying. After a
2944 * Blt the front buffer is a copy of the back buffer, and the back buffer is
2945 * untouched. Therefore it's necessary to override the swap effect
2946 * and to set it back after the flip.
2948 * Windowed Direct3D < 7 apps do the same. The D3D7 sdk demos are nice
2949 * testcases.
2952 dstSwapchain->presentParms.SwapEffect = WINED3DSWAPEFFECT_COPY;
2953 dstSwapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
2955 TRACE("Full screen back buffer -> front buffer blt, performing a flip instead\n");
2956 IWineD3DSwapChain_Present((IWineD3DSwapChain *) dstSwapchain, NULL, NULL, 0, NULL, 0);
2958 dstSwapchain->presentParms.SwapEffect = orig_swap;
2960 return WINED3D_OK;
2962 break;
2965 TRACE("Unsupported blit between buffers on the same swapchain\n");
2966 return WINED3DERR_INVALIDCALL;
2967 } else if(dstSwapchain && dstSwapchain == srcSwapchain) {
2968 FIXME("Implement hardware blit between two surfaces on the same swapchain\n");
2969 return WINED3DERR_INVALIDCALL;
2970 } else if(dstSwapchain && srcSwapchain) {
2971 FIXME("Implement hardware blit between two different swapchains\n");
2972 return WINED3DERR_INVALIDCALL;
2973 } else if(dstSwapchain) {
2974 if(SrcSurface == myDevice->render_targets[0]) {
2975 TRACE("Blit from active render target to a swapchain\n");
2976 /* Handled with regular texture -> swapchain blit */
2978 } else if(srcSwapchain && This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
2979 FIXME("Implement blit from a swapchain to the active render target\n");
2980 return WINED3DERR_INVALIDCALL;
2983 if((srcSwapchain || SrcSurface == myDevice->render_targets[0]) && !dstSwapchain) {
2984 /* Blit from render target to texture */
2985 WINED3DRECT srect;
2986 BOOL upsideDown, stretchx;
2988 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
2989 TRACE("Color keying not supported by frame buffer to texture blit\n");
2990 return WINED3DERR_INVALIDCALL;
2991 /* Destination color key is checked above */
2994 /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
2995 * glCopyTexSubImage is a bit picky about the parameters we pass to it
2997 if(SrcRect) {
2998 if(SrcRect->top < SrcRect->bottom) {
2999 srect.y1 = SrcRect->top;
3000 srect.y2 = SrcRect->bottom;
3001 upsideDown = FALSE;
3002 } else {
3003 srect.y1 = SrcRect->bottom;
3004 srect.y2 = SrcRect->top;
3005 upsideDown = TRUE;
3007 srect.x1 = SrcRect->left;
3008 srect.x2 = SrcRect->right;
3009 } else {
3010 srect.x1 = 0;
3011 srect.y1 = 0;
3012 srect.x2 = Src->currentDesc.Width;
3013 srect.y2 = Src->currentDesc.Height;
3014 upsideDown = FALSE;
3016 if(rect.x1 > rect.x2) {
3017 UINT tmp = rect.x2;
3018 rect.x2 = rect.x1;
3019 rect.x1 = tmp;
3020 upsideDown = !upsideDown;
3022 if(!srcSwapchain) {
3023 TRACE("Reading from an offscreen target\n");
3024 upsideDown = !upsideDown;
3027 if(rect.x2 - rect.x1 != srect.x2 - srect.x1) {
3028 stretchx = TRUE;
3029 } else {
3030 stretchx = FALSE;
3033 /* Blt is a pretty powerful call, while glCopyTexSubImage2D is not. glCopyTexSubImage cannot
3034 * flip the image nor scale it.
3036 * -> If the app asks for a unscaled, upside down copy, just perform one glCopyTexSubImage2D call
3037 * -> If the app wants a image width an unscaled width, copy it line per line
3038 * -> If the app wants a image that is scaled on the x axis, and the destination rectangle is smaller
3039 * than the frame buffer, draw an upside down scaled image onto the fb, read it back and restore the
3040 * back buffer. This is slower than reading line per line, thus not used for flipping
3041 * -> If the app wants a scaled image with a dest rect that is bigger than the fb, it has to be copied
3042 * pixel by pixel
3044 * If EXT_framebuffer_blit is supported that can be used instead. Note that EXT_framebuffer_blit implies
3045 * FBO support, so it doesn't really make sense to try and make it work with different offscreen rendering
3046 * backends.
3048 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && GL_SUPPORT(EXT_FRAMEBUFFER_BLIT)) {
3049 stretch_rect_fbo((IWineD3DDevice *)myDevice, SrcSurface, &srect,
3050 (IWineD3DSurface *)This, &rect, Filter, upsideDown);
3051 } else if((!stretchx) || rect.x2 - rect.x1 > Src->currentDesc.Width ||
3052 rect.y2 - rect.y1 > Src->currentDesc.Height) {
3053 TRACE("No stretching in x direction, using direct framebuffer -> texture copy\n");
3054 fb_copy_to_texture_direct(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
3055 } else {
3056 TRACE("Using hardware stretching to flip / stretch the texture\n");
3057 fb_copy_to_texture_hwstretch(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
3060 if(!(This->Flags & SFLAG_DONOTFREE)) {
3061 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
3062 This->resource.allocatedMemory = NULL;
3063 This->resource.heapMemory = NULL;
3064 } else {
3065 This->Flags &= ~SFLAG_INSYSMEM;
3067 /* The texture is now most up to date - If the surface is a render target and has a drawable, this
3068 * path is never entered
3070 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) This, SFLAG_INTEXTURE, TRUE);
3072 return WINED3D_OK;
3073 } else if(Src) {
3074 /* Blit from offscreen surface to render target */
3075 float glTexCoord[4];
3076 DWORD oldCKeyFlags = Src->CKeyFlags;
3077 WINEDDCOLORKEY oldBltCKey = This->SrcBltCKey;
3078 RECT SourceRectangle;
3080 TRACE("Blt from surface %p to rendertarget %p\n", Src, This);
3082 if(SrcRect) {
3083 SourceRectangle.left = SrcRect->left;
3084 SourceRectangle.right = SrcRect->right;
3085 SourceRectangle.top = SrcRect->top;
3086 SourceRectangle.bottom = SrcRect->bottom;
3087 } else {
3088 SourceRectangle.left = 0;
3089 SourceRectangle.right = Src->currentDesc.Width;
3090 SourceRectangle.top = 0;
3091 SourceRectangle.bottom = Src->currentDesc.Height;
3093 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && GL_SUPPORT(EXT_FRAMEBUFFER_BLIT) &&
3094 (Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) == 0) {
3095 TRACE("Using stretch_rect_fbo\n");
3096 /* The source is always a texture, but never the currently active render target, and the texture
3097 * contents are never upside down
3099 stretch_rect_fbo((IWineD3DDevice *)myDevice, SrcSurface, (WINED3DRECT *) &SourceRectangle,
3100 (IWineD3DSurface *)This, &rect, Filter, FALSE);
3101 return WINED3D_OK;
3104 if(!CalculateTexRect(Src, &SourceRectangle, glTexCoord)) {
3105 /* Fall back to software */
3106 WARN("(%p) Source texture area (%d,%d)-(%d,%d) is too big\n", Src,
3107 SourceRectangle.left, SourceRectangle.top,
3108 SourceRectangle.right, SourceRectangle.bottom);
3109 return WINED3DERR_INVALIDCALL;
3112 /* Color keying: Check if we have to do a color keyed blt,
3113 * and if not check if a color key is activated.
3115 * Just modify the color keying parameters in the surface and restore them afterwards
3116 * The surface keeps track of the color key last used to load the opengl surface.
3117 * PreLoad will catch the change to the flags and color key and reload if necessary.
3119 if(Flags & WINEDDBLT_KEYSRC) {
3120 /* Use color key from surface */
3121 } else if(Flags & WINEDDBLT_KEYSRCOVERRIDE) {
3122 /* Use color key from DDBltFx */
3123 Src->CKeyFlags |= WINEDDSD_CKSRCBLT;
3124 This->SrcBltCKey = DDBltFx->ddckSrcColorkey;
3125 } else {
3126 /* Do not use color key */
3127 Src->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
3130 /* Now load the surface */
3131 IWineD3DSurface_PreLoad((IWineD3DSurface *) Src);
3134 /* Activate the destination context, set it up for blitting */
3135 ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
3136 ENTER_GL();
3138 glEnable(Src->glDescription.target);
3139 checkGLcall("glEnable(Src->glDescription.target)");
3141 if(!dstSwapchain) {
3142 TRACE("Drawing to offscreen buffer\n");
3143 glDrawBuffer(myDevice->offscreenBuffer);
3144 checkGLcall("glDrawBuffer");
3145 } else {
3146 GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *)This, (IWineD3DSwapChain *)dstSwapchain);
3147 TRACE("Drawing to %#x buffer\n", buffer);
3148 glDrawBuffer(buffer);
3149 checkGLcall("glDrawBuffer");
3152 /* Bind the texture */
3153 glBindTexture(Src->glDescription.target, Src->glDescription.textureName);
3154 checkGLcall("glBindTexture");
3156 /* Filtering for StretchRect */
3157 glTexParameteri(Src->glDescription.target, GL_TEXTURE_MAG_FILTER,
3158 stateLookup[WINELOOKUP_MAGFILTER][Filter - minLookup[WINELOOKUP_MAGFILTER]]);
3159 checkGLcall("glTexParameteri");
3160 glTexParameteri(Src->glDescription.target, GL_TEXTURE_MIN_FILTER,
3161 minMipLookup[Filter][WINED3DTEXF_NONE]);
3162 checkGLcall("glTexParameteri");
3163 glTexParameteri(Src->glDescription.target, GL_TEXTURE_WRAP_S, GL_CLAMP);
3164 glTexParameteri(Src->glDescription.target, GL_TEXTURE_WRAP_T, GL_CLAMP);
3165 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
3166 checkGLcall("glTexEnvi");
3168 /* This is for color keying */
3169 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3170 glEnable(GL_ALPHA_TEST);
3171 checkGLcall("glEnable GL_ALPHA_TEST");
3172 glAlphaFunc(GL_NOTEQUAL, 0.0);
3173 checkGLcall("glAlphaFunc\n");
3174 } else {
3175 glDisable(GL_ALPHA_TEST);
3176 checkGLcall("glDisable GL_ALPHA_TEST");
3179 /* Draw a textured quad
3181 glBegin(GL_QUADS);
3183 glColor3d(1.0f, 1.0f, 1.0f);
3184 glTexCoord2f(glTexCoord[0], glTexCoord[2]);
3185 glVertex3f(rect.x1,
3186 rect.y1,
3187 0.0);
3189 glTexCoord2f(glTexCoord[0], glTexCoord[3]);
3190 glVertex3f(rect.x1, rect.y2, 0.0);
3192 glTexCoord2f(glTexCoord[1], glTexCoord[3]);
3193 glVertex3f(rect.x2,
3194 rect.y2,
3195 0.0);
3197 glTexCoord2f(glTexCoord[1], glTexCoord[2]);
3198 glVertex3f(rect.x2,
3199 rect.y1,
3200 0.0);
3201 glEnd();
3202 checkGLcall("glEnd");
3204 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3205 glDisable(GL_ALPHA_TEST);
3206 checkGLcall("glDisable(GL_ALPHA_TEST)");
3209 /* Flush in case the drawable is used by multiple GL contexts */
3210 if(dstSwapchain && (dstSwapchain->num_contexts >= 2))
3211 glFlush();
3213 glBindTexture(Src->glDescription.target, 0);
3214 checkGLcall("glBindTexture(Src->glDescription.target, 0)");
3215 /* Leave the opengl state valid for blitting */
3216 glDisable(Src->glDescription.target);
3217 checkGLcall("glDisable(Src->glDescription.target)");
3219 /* The draw buffer should only need to be restored if we were drawing to the front buffer, and there is a back buffer.
3220 * otherwise the context manager should choose between GL_BACK / offscreenDrawBuffer
3222 if(dstSwapchain && This == (IWineD3DSurfaceImpl *) dstSwapchain->frontBuffer && dstSwapchain->backBuffer) {
3223 glDrawBuffer(GL_BACK);
3224 checkGLcall("glDrawBuffer");
3226 /* Restore the color key parameters */
3227 Src->CKeyFlags = oldCKeyFlags;
3228 This->SrcBltCKey = oldBltCKey;
3230 LEAVE_GL();
3232 /* TODO: If the surface is locked often, perform the Blt in software on the memory instead */
3233 /* The surface is now in the drawable. On onscreen surfaces or without fbos the texture
3234 * is outdated now
3236 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) This, SFLAG_INDRAWABLE, TRUE);
3237 /* TODO: This should be moved to ModifyLocation() */
3238 if(!(dstSwapchain || wined3d_settings.offscreen_rendering_mode != ORM_FBO)) {
3239 This->Flags |= SFLAG_INTEXTURE;
3242 return WINED3D_OK;
3243 } else {
3244 /* Source-Less Blit to render target */
3245 if (Flags & WINEDDBLT_COLORFILL) {
3246 /* This is easy to handle for the D3D Device... */
3247 DWORD color;
3249 TRACE("Colorfill\n");
3251 /* This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0] || dstSwapchain
3252 must be true if we are here */
3253 if (This != (IWineD3DSurfaceImpl *) myDevice->render_targets[0] &&
3254 !(This == (IWineD3DSurfaceImpl*) dstSwapchain->frontBuffer ||
3255 (dstSwapchain->backBuffer && This == (IWineD3DSurfaceImpl*) dstSwapchain->backBuffer[0]))) {
3256 TRACE("Surface is higher back buffer, falling back to software\n");
3257 return WINED3DERR_INVALIDCALL;
3260 /* The color as given in the Blt function is in the format of the frame-buffer...
3261 * 'clear' expect it in ARGB format => we need to do some conversion :-)
3263 if (This->resource.format == WINED3DFMT_P8) {
3264 if (This->palette) {
3265 color = ((0xFF000000) |
3266 (This->palette->palents[DDBltFx->u5.dwFillColor].peRed << 16) |
3267 (This->palette->palents[DDBltFx->u5.dwFillColor].peGreen << 8) |
3268 (This->palette->palents[DDBltFx->u5.dwFillColor].peBlue));
3269 } else {
3270 color = 0xFF000000;
3273 else if (This->resource.format == WINED3DFMT_R5G6B5) {
3274 if (DDBltFx->u5.dwFillColor == 0xFFFF) {
3275 color = 0xFFFFFFFF;
3276 } else {
3277 color = ((0xFF000000) |
3278 ((DDBltFx->u5.dwFillColor & 0xF800) << 8) |
3279 ((DDBltFx->u5.dwFillColor & 0x07E0) << 5) |
3280 ((DDBltFx->u5.dwFillColor & 0x001F) << 3));
3283 else if ((This->resource.format == WINED3DFMT_R8G8B8) ||
3284 (This->resource.format == WINED3DFMT_X8R8G8B8) ) {
3285 color = 0xFF000000 | DDBltFx->u5.dwFillColor;
3287 else if (This->resource.format == WINED3DFMT_A8R8G8B8) {
3288 color = DDBltFx->u5.dwFillColor;
3290 else {
3291 ERR("Wrong surface type for BLT override(Format doesn't match) !\n");
3292 return WINED3DERR_INVALIDCALL;
3295 TRACE("(%p) executing Render Target override, color = %x\n", This, color);
3296 IWineD3DDeviceImpl_ClearSurface(myDevice, This,
3297 1, /* Number of rectangles */
3298 &rect, WINED3DCLEAR_TARGET, color,
3299 0.0 /* Z */,
3300 0 /* Stencil */);
3301 return WINED3D_OK;
3305 /* Default: Fall back to the generic blt. Not an error, a TRACE is enough */
3306 TRACE("Didn't find any usable render target setup for hw blit, falling back to software\n");
3307 return WINED3DERR_INVALIDCALL;
3310 static HRESULT WINAPI IWineD3DSurfaceImpl_BltZ(IWineD3DSurfaceImpl *This, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx)
3312 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3313 float depth;
3315 if (Flags & WINEDDBLT_DEPTHFILL) {
3316 switch(This->resource.format) {
3317 case WINED3DFMT_D16:
3318 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000ffff;
3319 break;
3320 case WINED3DFMT_D15S1:
3321 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000fffe;
3322 break;
3323 case WINED3DFMT_D24S8:
3324 case WINED3DFMT_D24X8:
3325 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00ffffff;
3326 break;
3327 case WINED3DFMT_D32:
3328 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0xffffffff;
3329 break;
3330 default:
3331 depth = 0.0;
3332 ERR("Unexpected format for depth fill: %s\n", debug_d3dformat(This->resource.format));
3335 return IWineD3DDevice_Clear((IWineD3DDevice *) myDevice,
3336 DestRect == NULL ? 0 : 1,
3337 (WINED3DRECT *) DestRect,
3338 WINED3DCLEAR_ZBUFFER,
3339 0x00000000,
3340 depth,
3341 0x00000000);
3344 FIXME("(%p): Unsupp depthstencil blit\n", This);
3345 return WINED3DERR_INVALIDCALL;
3348 static HRESULT WINAPI IWineD3DSurfaceImpl_Blt(IWineD3DSurface *iface, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
3349 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3350 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
3351 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3352 TRACE("(%p)->(%p,%p,%p,%x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3353 TRACE("(%p): Usage is %s\n", This, debug_d3dusage(This->resource.usage));
3355 /* Accessing the depth stencil is supposed to fail between a BeginScene and EndScene pair,
3356 * except depth blits, which seem to work
3358 if(iface == myDevice->stencilBufferTarget || (SrcSurface && SrcSurface == myDevice->stencilBufferTarget)) {
3359 if(myDevice->inScene && !(Flags & WINEDDBLT_DEPTHFILL)) {
3360 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3361 return WINED3DERR_INVALIDCALL;
3362 } else if(IWineD3DSurfaceImpl_BltZ(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx) == WINED3D_OK) {
3363 TRACE("Z Blit override handled the blit\n");
3364 return WINED3D_OK;
3368 /* Special cases for RenderTargets */
3369 if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3370 ( Src && (Src->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3371 if(IWineD3DSurfaceImpl_BltOverride(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter) == WINED3D_OK) return WINED3D_OK;
3374 /* For the rest call the X11 surface implementation.
3375 * For RenderTargets this should be implemented OpenGL accelerated in BltOverride,
3376 * other Blts are rather rare
3378 return IWineD3DBaseSurfaceImpl_Blt(iface, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter);
3381 HRESULT WINAPI IWineD3DSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty, IWineD3DSurface *Source, RECT *rsrc, DWORD trans) {
3382 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3383 IWineD3DSurfaceImpl *srcImpl = (IWineD3DSurfaceImpl *) Source;
3384 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3385 TRACE("(%p)->(%d, %d, %p, %p, %08x\n", iface, dstx, dsty, Source, rsrc, trans);
3387 if(myDevice->inScene &&
3388 (iface == myDevice->stencilBufferTarget ||
3389 (Source && Source == myDevice->stencilBufferTarget))) {
3390 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3391 return WINED3DERR_INVALIDCALL;
3394 /* Special cases for RenderTargets */
3395 if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3396 ( srcImpl && (srcImpl->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3398 RECT SrcRect, DstRect;
3399 DWORD Flags=0;
3401 if(rsrc) {
3402 SrcRect.left = rsrc->left;
3403 SrcRect.top= rsrc->top;
3404 SrcRect.bottom = rsrc->bottom;
3405 SrcRect.right = rsrc->right;
3406 } else {
3407 SrcRect.left = 0;
3408 SrcRect.top = 0;
3409 SrcRect.right = srcImpl->currentDesc.Width;
3410 SrcRect.bottom = srcImpl->currentDesc.Height;
3413 DstRect.left = dstx;
3414 DstRect.top=dsty;
3415 DstRect.right = dstx + SrcRect.right - SrcRect.left;
3416 DstRect.bottom = dsty + SrcRect.bottom - SrcRect.top;
3418 /* Convert BltFast flags into Btl ones because it is called from SurfaceImpl_Blt as well */
3419 if(trans & WINEDDBLTFAST_SRCCOLORKEY)
3420 Flags |= WINEDDBLT_KEYSRC;
3421 if(trans & WINEDDBLTFAST_DESTCOLORKEY)
3422 Flags |= WINEDDBLT_KEYDEST;
3423 if(trans & WINEDDBLTFAST_WAIT)
3424 Flags |= WINEDDBLT_WAIT;
3425 if(trans & WINEDDBLTFAST_DONOTWAIT)
3426 Flags |= WINEDDBLT_DONOTWAIT;
3428 if(IWineD3DSurfaceImpl_BltOverride(This, &DstRect, Source, &SrcRect, Flags, NULL, WINED3DTEXF_POINT) == WINED3D_OK) return WINED3D_OK;
3432 return IWineD3DBaseSurfaceImpl_BltFast(iface, dstx, dsty, Source, rsrc, trans);
3435 static HRESULT WINAPI IWineD3DSurfaceImpl_PrivateSetup(IWineD3DSurface *iface) {
3436 /** Check against the maximum texture sizes supported by the video card **/
3437 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3438 unsigned int pow2Width, pow2Height;
3439 const GlPixelFormatDesc *glDesc;
3441 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
3442 /* Setup some glformat defaults */
3443 This->glDescription.glFormat = glDesc->glFormat;
3444 This->glDescription.glFormatInternal = glDesc->glInternal;
3445 This->glDescription.glType = glDesc->glType;
3447 This->glDescription.textureName = 0;
3448 This->glDescription.target = GL_TEXTURE_2D;
3450 /* Non-power2 support */
3451 if (GL_SUPPORT(ARB_TEXTURE_NON_POWER_OF_TWO)) {
3452 pow2Width = This->currentDesc.Width;
3453 pow2Height = This->currentDesc.Height;
3454 } else {
3455 /* Find the nearest pow2 match */
3456 pow2Width = pow2Height = 1;
3457 while (pow2Width < This->currentDesc.Width) pow2Width <<= 1;
3458 while (pow2Height < This->currentDesc.Height) pow2Height <<= 1;
3460 This->pow2Width = pow2Width;
3461 This->pow2Height = pow2Height;
3463 if (pow2Width > This->currentDesc.Width || pow2Height > This->currentDesc.Height) {
3464 WINED3DFORMAT Format = This->resource.format;
3465 /** TODO: add support for non power two compressed textures **/
3466 if (Format == WINED3DFMT_DXT1 || Format == WINED3DFMT_DXT2 || Format == WINED3DFMT_DXT3
3467 || Format == WINED3DFMT_DXT4 || Format == WINED3DFMT_DXT5) {
3468 FIXME("(%p) Compressed non-power-two textures are not supported w(%d) h(%d)\n",
3469 This, This->currentDesc.Width, This->currentDesc.Height);
3470 return WINED3DERR_NOTAVAILABLE;
3474 if(pow2Width != This->currentDesc.Width ||
3475 pow2Height != This->currentDesc.Height) {
3476 This->Flags |= SFLAG_NONPOW2;
3479 TRACE("%p\n", This);
3480 if ((This->pow2Width > GL_LIMITS(texture_size) || This->pow2Height > GL_LIMITS(texture_size)) && !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL))) {
3481 /* one of three options
3482 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)
3483 2: Set the texture to the maximum size (bad idea)
3484 3: WARN and return WINED3DERR_NOTAVAILABLE;
3485 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.
3487 WARN("(%p) Creating an oversized surface\n", This);
3488 This->Flags |= SFLAG_OVERSIZE;
3490 /* This will be initialized on the first blt */
3491 This->glRect.left = 0;
3492 This->glRect.top = 0;
3493 This->glRect.right = 0;
3494 This->glRect.bottom = 0;
3495 } else {
3496 /* Check this after the oversize check - do not make an oversized surface a texture_rectangle one */
3497 if(This->Flags & SFLAG_NONPOW2 && GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
3498 This->glDescription.target = GL_TEXTURE_RECTANGLE_ARB;
3499 This->pow2Width = This->currentDesc.Width;
3500 This->pow2Height = This->currentDesc.Height;
3501 This->Flags &= ~SFLAG_NONPOW2;
3504 /* No oversize, gl rect is the full texture size */
3505 This->Flags &= ~SFLAG_OVERSIZE;
3506 This->glRect.left = 0;
3507 This->glRect.top = 0;
3508 This->glRect.right = This->pow2Width;
3509 This->glRect.bottom = This->pow2Height;
3512 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
3513 switch(wined3d_settings.offscreen_rendering_mode) {
3514 case ORM_FBO: This->get_drawable_size = get_drawable_size_fbo; break;
3515 case ORM_PBUFFER: This->get_drawable_size = get_drawable_size_pbuffer; break;
3516 case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
3520 This->Flags |= SFLAG_INSYSMEM;
3522 return WINED3D_OK;
3525 static void WINAPI IWineD3DSurfaceImpl_ModifyLocation(IWineD3DSurface *iface, DWORD flag, BOOL persistent) {
3526 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3527 IWineD3DBaseTexture *texture;
3529 TRACE("(%p)->(%s, %s)\n", iface,
3530 flag == SFLAG_INSYSMEM ? "SFLAG_INSYSMEM" : flag == SFLAG_INDRAWABLE ? "SFLAG_INDRAWABLE" : "SFLAG_INTEXTURE",
3531 persistent ? "TRUE" : "FALSE");
3533 /* TODO: For offscreen textures with fbo offscreen rendering the drawable is the same as the texture.*/
3534 if(persistent) {
3535 if((This->Flags & SFLAG_INTEXTURE) && !(flag & SFLAG_INTEXTURE)) {
3536 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
3537 TRACE("Passing to container\n");
3538 IWineD3DBaseTexture_SetDirty(texture, TRUE);
3539 IWineD3DBaseTexture_Release(texture);
3542 This->Flags &= ~SFLAG_LOCATIONS;
3543 This->Flags |= flag;
3544 } else {
3545 if((This->Flags & SFLAG_INTEXTURE) && (flag & SFLAG_INTEXTURE)) {
3546 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
3547 TRACE("Passing to container\n");
3548 IWineD3DBaseTexture_SetDirty(texture, TRUE);
3549 IWineD3DBaseTexture_Release(texture);
3552 This->Flags &= ~flag;
3556 struct coords {
3557 int x, y, z;
3560 static inline void surface_blt_to_drawable(IWineD3DSurfaceImpl *This, const RECT *rect_in) {
3561 struct coords coords[4];
3562 RECT rect;
3563 IWineD3DSwapChain *swapchain = NULL;
3564 IWineD3DBaseTexture *texture = NULL;
3565 HRESULT hr;
3566 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
3568 if(rect_in) {
3569 rect = *rect_in;
3570 } else {
3571 rect.left = 0;
3572 rect.top = 0;
3573 rect.right = This->currentDesc.Width;
3574 rect.bottom = This->currentDesc.Height;
3577 ActivateContext(device, device->render_targets[0], CTXUSAGE_BLIT);
3578 ENTER_GL();
3580 if(This->glDescription.target == GL_TEXTURE_RECTANGLE_ARB) {
3581 glEnable(GL_TEXTURE_RECTANGLE_ARB);
3582 checkGLcall("glEnable(GL_TEXTURE_RECTANGLE_ARB)");
3583 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, This->glDescription.textureName);
3584 checkGLcall("GL_TEXTURE_RECTANGLE_ARB, This->glDescription.textureName)");
3585 glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
3586 checkGLcall("glTexParameteri");
3587 glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
3588 checkGLcall("glTexParameteri");
3590 coords[0].x = rect.left;
3591 coords[0].z = 0;
3593 coords[1].x = rect.left;
3594 coords[1].z = 0;
3596 coords[2].x = rect.right;
3597 coords[2].z = 0;
3599 coords[3].x = rect.right;
3600 coords[3].z = 0;
3602 coords[0].y = rect.top;
3603 coords[1].y = rect.bottom;
3604 coords[2].y = rect.bottom;
3605 coords[3].y = rect.top;
3606 } else if(This->glDescription.target == GL_TEXTURE_2D) {
3607 glEnable(GL_TEXTURE_2D);
3608 checkGLcall("glEnable(GL_TEXTURE_2D)");
3609 glBindTexture(GL_TEXTURE_2D, This->glDescription.textureName);
3610 checkGLcall("GL_TEXTURE_2D, This->glDescription.textureName)");
3611 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
3612 checkGLcall("glTexParameteri");
3613 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
3614 checkGLcall("glTexParameteri");
3616 coords[0].x = rect.left / This->pow2Width;
3617 coords[0].z = 0;
3619 coords[1].x = rect.left / This->pow2Width;
3620 coords[1].z = 0;
3622 coords[2].x = rect.right / This->pow2Width;
3623 coords[2].z = 0;
3625 coords[3].x = rect.right / This->pow2Width;
3626 coords[3].z = 0;
3628 coords[0].y = rect.top / This->pow2Height;
3629 coords[1].y = rect.bottom / This->pow2Height;
3630 coords[2].y = rect.bottom / This->pow2Height;
3631 coords[3].y = rect.top / This->pow2Height;
3632 } else {
3633 /* Must be a cube map */
3634 glEnable(GL_TEXTURE_CUBE_MAP_ARB);
3635 checkGLcall("glEnable(GL_TEXTURE_CUBE_MAP_ARB)");
3636 glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, This->glDescription.textureName);
3637 checkGLcall("GL_TEXTURE_CUBE_MAP_ARB, This->glDescription.textureName)");
3638 glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
3639 checkGLcall("glTexParameteri");
3640 glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
3641 checkGLcall("glTexParameteri");
3643 switch(This->glDescription.target) {
3644 case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
3645 coords[0].x = 1; coords[0].y = -1; coords[0].z = 1;
3646 coords[1].x = 1; coords[1].y = 1; coords[1].z = 1;
3647 coords[2].x = 1; coords[2].y = 1; coords[2].z = -1;
3648 coords[3].x = 1; coords[3].y = -1; coords[3].z = -1;
3649 break;
3651 case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
3652 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
3653 coords[1].x = -1; coords[1].y = 1; coords[1].z = 1;
3654 coords[2].x = -1; coords[2].y = 1; coords[2].z = -1;
3655 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
3656 break;
3658 case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
3659 coords[0].x = -1; coords[0].y = 1; coords[0].z = 1;
3660 coords[1].x = 1; coords[1].y = 1; coords[1].z = 1;
3661 coords[2].x = 1; coords[2].y = 1; coords[2].z = -1;
3662 coords[3].x = -1; coords[3].y = 1; coords[3].z = -1;
3663 break;
3665 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
3666 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
3667 coords[1].x = 1; coords[1].y = -1; coords[1].z = 1;
3668 coords[2].x = 1; coords[2].y = -1; coords[2].z = -1;
3669 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
3670 break;
3672 case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
3673 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
3674 coords[1].x = 1; coords[1].y = -1; coords[1].z = 1;
3675 coords[2].x = 1; coords[2].y = -1; coords[2].z = 1;
3676 coords[3].x = -1; coords[3].y = -1; coords[3].z = 1;
3677 break;
3679 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
3680 coords[0].x = -1; coords[0].y = -1; coords[0].z = -1;
3681 coords[1].x = 1; coords[1].y = -1; coords[1].z = -1;
3682 coords[2].x = 1; coords[2].y = -1; coords[2].z = -1;
3683 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
3685 default:
3686 ERR("Unexpected texture target\n");
3687 LEAVE_GL();
3688 return;
3692 glBegin(GL_QUADS);
3693 glTexCoord3iv((GLint *) &coords[0]);
3694 glVertex2i(rect.left, device->render_offscreen ? rect.bottom : rect.top);
3696 glTexCoord3iv((GLint *) &coords[1]);
3697 glVertex2i(0, device->render_offscreen ? rect.top : rect.bottom);
3699 glTexCoord3iv((GLint *) &coords[2]);
3700 glVertex2i(rect.right, device->render_offscreen ? rect.top : rect.bottom);
3702 glTexCoord3iv((GLint *) &coords[3]);
3703 glVertex2i(rect.right, device->render_offscreen ? rect.bottom : rect.top);
3704 glEnd();
3705 checkGLcall("glEnd");
3707 if(This->glDescription.target != GL_TEXTURE_2D) {
3708 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
3709 checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
3710 } else {
3711 glDisable(GL_TEXTURE_2D);
3712 checkGLcall("glDisable(GL_TEXTURE_2D)");
3715 hr = IWineD3DSurface_GetContainer((IWineD3DSurface*)This, &IID_IWineD3DSwapChain, (void **) &swapchain);
3716 if(hr == WINED3D_OK && swapchain) {
3717 /* Make sure to flush the buffers. This is needed in apps like Red Alert II and Tiberian SUN that use multiple WGL contexts. */
3718 if(((IWineD3DSwapChainImpl*)swapchain)->num_contexts >= 2)
3719 glFlush();
3721 IWineD3DSwapChain_Release(swapchain);
3722 } else {
3723 /* We changed the filtering settings on the texture. Inform the container about this to get the filters
3724 * reset properly next draw
3726 hr = IWineD3DSurface_GetContainer((IWineD3DSurface*)This, &IID_IWineD3DBaseTexture, (void **) &texture);
3727 if(hr == WINED3D_OK && texture) {
3728 ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
3729 ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
3730 ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
3731 IWineD3DBaseTexture_Release(texture);
3734 LEAVE_GL();
3737 /*****************************************************************************
3738 * IWineD3DSurface::LoadLocation
3740 * Copies the current surface data from wherever it is to the requested
3741 * location. The location is one of the surface flags, SFLAG_INSYSMEM,
3742 * SFLAG_INTEXTURE and SFLAG_INDRAWABLE. When the surface is current in
3743 * multiple locations, the gl texture is preferred over the drawable, which is
3744 * preferred over system memory. The PBO counts as system memory. If rect is
3745 * not NULL, only the specified rectangle is copied (only supported for
3746 * sysmem<->drawable copies at the moment). If rect is NULL, the destination
3747 * location is marked up to date after the copy.
3749 * Parameters:
3750 * flag: Surface location flag to be updated
3751 * rect: rectangle to be copied
3753 * Returns:
3754 * WINED3D_OK on success
3755 * WINED3DERR_DEVICELOST on an internal error
3757 *****************************************************************************/
3758 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadLocation(IWineD3DSurface *iface, DWORD flag, const RECT *rect) {
3759 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3760 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
3761 GLenum format, internal, type;
3762 CONVERT_TYPES convert;
3763 int bpp;
3764 int width, pitch, outpitch;
3765 BYTE *mem;
3767 TRACE("(%p)->(%s, %p)\n", iface,
3768 flag == SFLAG_INSYSMEM ? "SFLAG_INSYSMEM" : flag == SFLAG_INDRAWABLE ? "SFLAG_INDRAWABLE" : "SFLAG_INTEXTURE",
3769 rect);
3770 if(rect) {
3771 TRACE("Rectangle: (%d,%d)-(%d,%d)\n", rect->left, rect->top, rect->right, rect->bottom);
3774 /* TODO: For fbo targets, texture == drawable */
3775 if(This->Flags & flag) {
3776 TRACE("Location already up to date\n");
3777 return WINED3D_OK;
3780 if(!(This->Flags & SFLAG_LOCATIONS)) {
3781 ERR("Surface does not have any up to date location\n");
3782 This->Flags |= SFLAG_LOST;
3783 return WINED3DERR_DEVICELOST;
3786 if(flag == SFLAG_INSYSMEM) {
3787 surface_prepare_system_memory(This);
3789 /* Download the surface to system memory */
3790 if(This->Flags & SFLAG_INTEXTURE) {
3791 surface_download_data(This);
3792 } else {
3793 read_from_framebuffer(This, rect,
3794 This->resource.allocatedMemory,
3795 IWineD3DSurface_GetPitch(iface));
3797 } else if(flag == SFLAG_INDRAWABLE) {
3798 if(This->Flags & SFLAG_INTEXTURE) {
3799 surface_blt_to_drawable(This, rect);
3800 } else {
3801 flush_to_framebuffer_drawpixels(This);
3803 } else /* if(flag == SFLAG_INTEXTURE) */ {
3804 d3dfmt_get_conv(This, TRUE /* We need color keying */, TRUE /* We will use textures */, &format, &internal, &type, &convert, &bpp, This->srgb);
3806 if (This->Flags & SFLAG_INDRAWABLE) {
3807 GLint prevRead;
3809 ENTER_GL();
3810 glGetIntegerv(GL_READ_BUFFER, &prevRead);
3811 vcheckGLcall("glGetIntegerv");
3812 glReadBuffer(This->resource.wineD3DDevice->offscreenBuffer);
3813 vcheckGLcall("glReadBuffer");
3815 if(!(This->Flags & SFLAG_ALLOCATED)) {
3816 surface_allocate_surface(This, internal, This->pow2Width,
3817 This->pow2Height, format, type);
3820 clear_unused_channels(This);
3822 glCopyTexSubImage2D(This->glDescription.target,
3823 This->glDescription.level,
3824 0, 0, 0, 0,
3825 This->currentDesc.Width,
3826 This->currentDesc.Height);
3827 checkGLcall("glCopyTexSubImage2D");
3829 glReadBuffer(prevRead);
3830 vcheckGLcall("glReadBuffer");
3832 LEAVE_GL();
3834 TRACE("Updated target %d\n", This->glDescription.target);
3835 } else {
3836 /* The only place where LoadTexture() might get called when isInDraw=1
3837 * is ActivateContext where lastActiveRenderTarget is preloaded.
3839 if(iface == device->lastActiveRenderTarget && device->isInDraw)
3840 ERR("Reading back render target but SFLAG_INDRAWABLE not set\n");
3842 /* Otherwise: System memory copy must be most up to date */
3844 if(This->CKeyFlags & WINEDDSD_CKSRCBLT) {
3845 This->Flags |= SFLAG_GLCKEY;
3846 This->glCKey = This->SrcBltCKey;
3848 else This->Flags &= ~SFLAG_GLCKEY;
3850 /* The width is in 'length' not in bytes */
3851 width = This->currentDesc.Width;
3852 pitch = IWineD3DSurface_GetPitch(iface);
3854 if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
3855 int height = This->currentDesc.Height;
3857 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
3858 outpitch = width * bpp;
3859 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
3861 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
3862 if(!mem) {
3863 ERR("Out of memory %d, %d!\n", outpitch, height);
3864 return WINED3DERR_OUTOFVIDEOMEMORY;
3866 d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
3868 This->Flags |= SFLAG_CONVERTED;
3869 } else if( (This->resource.format == WINED3DFMT_P8) && (GL_SUPPORT(EXT_PALETTED_TEXTURE) || GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) ) {
3870 d3dfmt_p8_upload_palette(iface, convert);
3871 This->Flags &= ~SFLAG_CONVERTED;
3872 mem = This->resource.allocatedMemory;
3873 } else {
3874 This->Flags &= ~SFLAG_CONVERTED;
3875 mem = This->resource.allocatedMemory;
3878 /* Make sure the correct pitch is used */
3879 glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
3881 if ((This->Flags & SFLAG_NONPOW2) && !(This->Flags & SFLAG_OVERSIZE)) {
3882 TRACE("non power of two support\n");
3883 if(!(This->Flags & SFLAG_ALLOCATED)) {
3884 surface_allocate_surface(This, internal, This->pow2Width, This->pow2Height, format, type);
3886 if (mem || (This->Flags & SFLAG_PBO)) {
3887 surface_upload_data(This, internal, This->currentDesc.Width, This->currentDesc.Height, format, type, mem);
3889 } else {
3890 /* When making the realloc conditional, keep in mind that GL_APPLE_client_storage may be in use, and This->resource.allocatedMemory
3891 * changed. So also keep track of memory changes. In this case the texture has to be reallocated
3893 if(!(This->Flags & SFLAG_ALLOCATED)) {
3894 surface_allocate_surface(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type);
3896 if (mem || (This->Flags & SFLAG_PBO)) {
3897 surface_upload_data(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type, mem);
3901 /* Restore the default pitch */
3902 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
3904 /* Don't delete PBO memory */
3905 if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
3906 HeapFree(GetProcessHeap(), 0, mem);
3910 if(rect == NULL) {
3911 This->Flags |= flag;
3914 return WINED3D_OK;
3917 HRESULT WINAPI IWineD3DSurfaceImpl_SetContainer(IWineD3DSurface *iface, IWineD3DBase *container) {
3918 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3919 IWineD3DSwapChain *swapchain = NULL;
3921 /* Update the drawable size method */
3922 if(container) {
3923 IWineD3DBase_QueryInterface(container, &IID_IWineD3DSwapChain, (void **) &swapchain);
3925 if(swapchain) {
3926 This->get_drawable_size = get_drawable_size_swapchain;
3927 IWineD3DSwapChain_Release(swapchain);
3928 } else if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
3929 switch(wined3d_settings.offscreen_rendering_mode) {
3930 case ORM_FBO: This->get_drawable_size = get_drawable_size_fbo; break;
3931 case ORM_PBUFFER: This->get_drawable_size = get_drawable_size_pbuffer; break;
3932 case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
3936 return IWineD3DBaseSurfaceImpl_SetContainer(iface, container);
3939 const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl =
3941 /* IUnknown */
3942 IWineD3DBaseSurfaceImpl_QueryInterface,
3943 IWineD3DBaseSurfaceImpl_AddRef,
3944 IWineD3DSurfaceImpl_Release,
3945 /* IWineD3DResource */
3946 IWineD3DBaseSurfaceImpl_GetParent,
3947 IWineD3DBaseSurfaceImpl_GetDevice,
3948 IWineD3DBaseSurfaceImpl_SetPrivateData,
3949 IWineD3DBaseSurfaceImpl_GetPrivateData,
3950 IWineD3DBaseSurfaceImpl_FreePrivateData,
3951 IWineD3DBaseSurfaceImpl_SetPriority,
3952 IWineD3DBaseSurfaceImpl_GetPriority,
3953 IWineD3DSurfaceImpl_PreLoad,
3954 IWineD3DBaseSurfaceImpl_GetType,
3955 /* IWineD3DSurface */
3956 IWineD3DBaseSurfaceImpl_GetContainer,
3957 IWineD3DBaseSurfaceImpl_GetDesc,
3958 IWineD3DSurfaceImpl_LockRect,
3959 IWineD3DSurfaceImpl_UnlockRect,
3960 IWineD3DSurfaceImpl_GetDC,
3961 IWineD3DSurfaceImpl_ReleaseDC,
3962 IWineD3DSurfaceImpl_Flip,
3963 IWineD3DSurfaceImpl_Blt,
3964 IWineD3DBaseSurfaceImpl_GetBltStatus,
3965 IWineD3DBaseSurfaceImpl_GetFlipStatus,
3966 IWineD3DBaseSurfaceImpl_IsLost,
3967 IWineD3DBaseSurfaceImpl_Restore,
3968 IWineD3DSurfaceImpl_BltFast,
3969 IWineD3DBaseSurfaceImpl_GetPalette,
3970 IWineD3DBaseSurfaceImpl_SetPalette,
3971 IWineD3DBaseSurfaceImpl_RealizePalette,
3972 IWineD3DBaseSurfaceImpl_SetColorKey,
3973 IWineD3DBaseSurfaceImpl_GetPitch,
3974 IWineD3DSurfaceImpl_SetMem,
3975 IWineD3DBaseSurfaceImpl_SetOverlayPosition,
3976 IWineD3DBaseSurfaceImpl_GetOverlayPosition,
3977 IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder,
3978 IWineD3DBaseSurfaceImpl_UpdateOverlay,
3979 IWineD3DBaseSurfaceImpl_SetClipper,
3980 IWineD3DBaseSurfaceImpl_GetClipper,
3981 /* Internal use: */
3982 IWineD3DSurfaceImpl_AddDirtyRect,
3983 IWineD3DSurfaceImpl_LoadTexture,
3984 IWineD3DSurfaceImpl_BindTexture,
3985 IWineD3DSurfaceImpl_SaveSnapshot,
3986 IWineD3DSurfaceImpl_SetContainer,
3987 IWineD3DSurfaceImpl_SetGlTextureDesc,
3988 IWineD3DSurfaceImpl_GetGlDesc,
3989 IWineD3DSurfaceImpl_GetData,
3990 IWineD3DSurfaceImpl_SetFormat,
3991 IWineD3DSurfaceImpl_PrivateSetup,
3992 IWineD3DSurfaceImpl_ModifyLocation,
3993 IWineD3DSurfaceImpl_LoadLocation