push a9ea98eed33411fd355fd4e8b78f7880f1dd09a3
[wine/hacks.git] / dlls / wined3d / surface.c
blob0628e5a528da058284d15bd809b28902f8e6618e
1 /*
2 * IWineD3DSurface Implementation
4 * Copyright 1998 Lionel Ulmer
5 * Copyright 2000-2001 TransGaming Technologies Inc.
6 * Copyright 2002-2005 Jason Edmeades
7 * Copyright 2002-2003 Raphael Junqueira
8 * Copyright 2004 Christian Costa
9 * Copyright 2005 Oliver Stieber
10 * Copyright 2006-2008 Stefan Dösinger for CodeWeavers
11 * Copyright 2007-2008 Henri Verbeet
12 * Copyright 2006-2008 Roderick Colenbrander
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);
38 static void d3dfmt_p8_upload_palette(IWineD3DSurface *iface, CONVERT_TYPES convert);
39 static inline void clear_unused_channels(IWineD3DSurfaceImpl *This);
40 static void surface_remove_pbo(IWineD3DSurfaceImpl *This);
42 static void surface_bind_and_dirtify(IWineD3DSurfaceImpl *This) {
43 int active_sampler;
45 /* We don't need a specific texture unit, but after binding the texture the current unit is dirty.
46 * Read the unit back instead of switching to 0, this avoids messing around with the state manager's
47 * gl states. The current texture unit should always be a valid one.
49 * TODO: Track the current active texture per GL context instead of using glGet
51 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
52 GLint active_texture;
53 ENTER_GL();
54 glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
55 LEAVE_GL();
56 active_sampler = This->resource.wineD3DDevice->rev_tex_unit_map[active_texture - GL_TEXTURE0_ARB];
57 } else {
58 active_sampler = 0;
61 if (active_sampler != -1) {
62 IWineD3DDeviceImpl_MarkStateDirty(This->resource.wineD3DDevice, STATE_SAMPLER(active_sampler));
64 IWineD3DSurface_BindTexture((IWineD3DSurface *)This);
67 /* This function checks if the primary render target uses the 8bit paletted format. */
68 static BOOL primary_render_target_is_p8(IWineD3DDeviceImpl *device)
70 if (device->render_targets && device->render_targets[0]) {
71 IWineD3DSurfaceImpl* render_target = (IWineD3DSurfaceImpl*)device->render_targets[0];
72 if((render_target->resource.usage & WINED3DUSAGE_RENDERTARGET) && (render_target->resource.format == WINED3DFMT_P8))
73 return TRUE;
75 return FALSE;
78 /* This call just downloads data, the caller is responsible for activating the
79 * right context and binding the correct texture. */
80 static void surface_download_data(IWineD3DSurfaceImpl *This) {
81 if (0 == This->glDescription.textureName) {
82 ERR("Surface does not have a texture, but SFLAG_INTEXTURE is set\n");
83 return;
86 /* Only support read back of converted P8 surfaces */
87 if(This->Flags & SFLAG_CONVERTED && (This->resource.format != WINED3DFMT_P8)) {
88 FIXME("Read back converted textures unsupported, format=%s\n", debug_d3dformat(This->resource.format));
89 return;
92 ENTER_GL();
94 if (This->resource.format == WINED3DFMT_DXT1 ||
95 This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
96 This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5 ||
97 This->resource.format == WINED3DFMT_ATI2N) {
98 if (!GL_SUPPORT(EXT_TEXTURE_COMPRESSION_S3TC)) { /* We can assume this as the texture would not have been created otherwise */
99 FIXME("(%p) : Attempting to lock a compressed texture when texture compression isn't supported by opengl\n", This);
100 } else {
101 TRACE("(%p) : Calling glGetCompressedTexImageARB level %d, format %#x, type %#x, data %p\n", This, This->glDescription.level,
102 This->glDescription.glFormat, This->glDescription.glType, This->resource.allocatedMemory);
104 if(This->Flags & SFLAG_PBO) {
105 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
106 checkGLcall("glBindBufferARB");
107 GL_EXTCALL(glGetCompressedTexImageARB(This->glDescription.target, This->glDescription.level, NULL));
108 checkGLcall("glGetCompressedTexImageARB()");
109 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
110 checkGLcall("glBindBufferARB");
111 } else {
112 GL_EXTCALL(glGetCompressedTexImageARB(This->glDescription.target, This->glDescription.level, This->resource.allocatedMemory));
113 checkGLcall("glGetCompressedTexImageARB()");
116 LEAVE_GL();
117 } else {
118 void *mem;
119 GLenum format = This->glDescription.glFormat;
120 GLenum type = This->glDescription.glType;
121 int src_pitch = 0;
122 int dst_pitch = 0;
124 /* In case of P8 the index is stored in the alpha component if the primary render target uses P8 */
125 if(This->resource.format == WINED3DFMT_P8 && primary_render_target_is_p8(This->resource.wineD3DDevice)) {
126 format = GL_ALPHA;
127 type = GL_UNSIGNED_BYTE;
130 if (This->Flags & SFLAG_NONPOW2) {
131 unsigned char alignment = This->resource.wineD3DDevice->surface_alignment;
132 src_pitch = This->bytesPerPixel * This->pow2Width;
133 dst_pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);
134 src_pitch = (src_pitch + alignment - 1) & ~(alignment - 1);
135 mem = HeapAlloc(GetProcessHeap(), 0, src_pitch * This->pow2Height);
136 } else {
137 mem = This->resource.allocatedMemory;
140 TRACE("(%p) : Calling glGetTexImage level %d, format %#x, type %#x, data %p\n", This, This->glDescription.level,
141 format, type, mem);
143 if(This->Flags & SFLAG_PBO) {
144 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
145 checkGLcall("glBindBufferARB");
147 glGetTexImage(This->glDescription.target, This->glDescription.level, format,
148 type, NULL);
149 checkGLcall("glGetTexImage()");
151 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
152 checkGLcall("glBindBufferARB");
153 } else {
154 glGetTexImage(This->glDescription.target, This->glDescription.level, format,
155 type, mem);
156 checkGLcall("glGetTexImage()");
158 LEAVE_GL();
160 if (This->Flags & SFLAG_NONPOW2) {
161 LPBYTE src_data, dst_data;
162 int y;
164 * Some games (e.g. warhammer 40k) don't work properly with the odd pitches, preventing
165 * the surface pitch from being used to box non-power2 textures. Instead we have to use a hack to
166 * repack the texture so that the bpp * width pitch can be used instead of bpp * pow2width.
168 * We're doing this...
170 * instead of boxing the texture :
171 * |<-texture width ->| -->pow2width| /\
172 * |111111111111111111| | |
173 * |222 Texture 222222| boxed empty | texture height
174 * |3333 Data 33333333| | |
175 * |444444444444444444| | \/
176 * ----------------------------------- |
177 * | boxed empty | boxed empty | pow2height
178 * | | | \/
179 * -----------------------------------
182 * we're repacking the data to the expected texture width
184 * |<-texture width ->| -->pow2width| /\
185 * |111111111111111111222222222222222| |
186 * |222333333333333333333444444444444| texture height
187 * |444444 | |
188 * | | \/
189 * | | |
190 * | empty | pow2height
191 * | | \/
192 * -----------------------------------
194 * == is the same as
196 * |<-texture width ->| /\
197 * |111111111111111111|
198 * |222222222222222222|texture height
199 * |333333333333333333|
200 * |444444444444444444| \/
201 * --------------------
203 * this also means that any references to allocatedMemory should work with the data as if were a
204 * standard texture with a non-power2 width instead of texture boxed up to be a power2 texture.
206 * internally the texture is still stored in a boxed format so any references to textureName will
207 * get a boxed texture with width pow2width and not a texture of width currentDesc.Width.
209 * Performance should not be an issue, because applications normally do not lock the surfaces when
210 * rendering. If an app does, the SFLAG_DYNLOCK flag will kick in and the memory copy won't be released,
211 * and doesn't have to be re-read.
213 src_data = mem;
214 dst_data = This->resource.allocatedMemory;
215 TRACE("(%p) : Repacking the surface data from pitch %d to pitch %d\n", This, src_pitch, dst_pitch);
216 for (y = 1 ; y < This->currentDesc.Height; y++) {
217 /* skip the first row */
218 src_data += src_pitch;
219 dst_data += dst_pitch;
220 memcpy(dst_data, src_data, dst_pitch);
223 HeapFree(GetProcessHeap(), 0, mem);
227 /* Surface has now been downloaded */
228 This->Flags |= SFLAG_INSYSMEM;
231 /* This call just uploads data, the caller is responsible for activating the
232 * right context and binding the correct texture. */
233 static void surface_upload_data(IWineD3DSurfaceImpl *This, GLenum internal, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *data) {
234 if (This->resource.format == WINED3DFMT_DXT1 ||
235 This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
236 This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5 ||
237 This->resource.format == WINED3DFMT_ATI2N) {
238 if (!GL_SUPPORT(EXT_TEXTURE_COMPRESSION_S3TC)) {
239 FIXME("Using DXT1/3/5 without advertized support\n");
240 } else {
241 /* glCompressedTexSubImage2D for uploading and glTexImage2D for allocating does not work well on some drivers(r200 dri, MacOS ATI driver)
242 * glCompressedTexImage2D does not accept NULL pointers. So for compressed textures surface_allocate_surface does nothing, and this
243 * function uses glCompressedTexImage2D instead of the SubImage call
245 TRACE("(%p) : Calling glCompressedTexSubImage2D w %d, h %d, data %p\n", This, width, height, data);
246 ENTER_GL();
248 if(This->Flags & SFLAG_PBO) {
249 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
250 checkGLcall("glBindBufferARB");
251 TRACE("(%p) pbo: %#x, data: %p\n", This, This->pbo, data);
253 GL_EXTCALL(glCompressedTexImage2DARB(This->glDescription.target, This->glDescription.level, internal,
254 width, height, 0 /* border */, This->resource.size, NULL));
255 checkGLcall("glCompressedTexSubImage2D");
257 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
258 checkGLcall("glBindBufferARB");
259 } else {
260 GL_EXTCALL(glCompressedTexImage2DARB(This->glDescription.target, This->glDescription.level, internal,
261 width, height, 0 /* border */, This->resource.size, data));
262 checkGLcall("glCompressedTexSubImage2D");
264 LEAVE_GL();
266 } else {
267 TRACE("(%p) : Calling glTexSubImage2D w %d, h %d, data, %p\n", This, width, height, data);
268 ENTER_GL();
270 if(This->Flags & SFLAG_PBO) {
271 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
272 checkGLcall("glBindBufferARB");
273 TRACE("(%p) pbo: %#x, data: %p\n", This, This->pbo, data);
275 glTexSubImage2D(This->glDescription.target, This->glDescription.level, 0, 0, width, height, format, type, NULL);
276 checkGLcall("glTexSubImage2D");
278 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
279 checkGLcall("glBindBufferARB");
281 else {
282 glTexSubImage2D(This->glDescription.target, This->glDescription.level, 0, 0, width, height, format, type, data);
283 checkGLcall("glTexSubImage2D");
286 LEAVE_GL();
290 /* This call just allocates the texture, the caller is responsible for
291 * activating the right context and binding the correct texture. */
292 static void surface_allocate_surface(IWineD3DSurfaceImpl *This, GLenum internal, GLsizei width, GLsizei height, GLenum format, GLenum type) {
293 BOOL enable_client_storage = FALSE;
294 BYTE *mem = NULL;
296 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,
297 This->glDescription.target, This->glDescription.level, debug_d3dformat(This->resource.format), internal, width, height, format, type);
299 if (This->resource.format == WINED3DFMT_DXT1 ||
300 This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
301 This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5 ||
302 This->resource.format == WINED3DFMT_ATI2N) {
303 /* glCompressedTexImage2D does not accept NULL pointers, so we cannot allocate a compressed texture without uploading data */
304 TRACE("Not allocating compressed surfaces, surface_upload_data will specify them\n");
306 /* We have to point GL to the client storage memory here, because upload_data might use a PBO. This means a double upload
307 * once, unfortunately
309 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
310 /* Neither NONPOW2, DIBSECTION nor OVERSIZE flags can be set on compressed textures */
311 This->Flags |= SFLAG_CLIENT;
312 mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
313 ENTER_GL();
314 GL_EXTCALL(glCompressedTexImage2DARB(This->glDescription.target, This->glDescription.level, internal,
315 width, height, 0 /* border */, This->resource.size, mem));
316 LEAVE_GL();
319 return;
322 ENTER_GL();
324 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
325 if(This->Flags & (SFLAG_NONPOW2 | SFLAG_DIBSECTION | SFLAG_OVERSIZE | SFLAG_CONVERTED) || This->resource.allocatedMemory == NULL) {
326 /* In some cases we want to disable client storage.
327 * SFLAG_NONPOW2 has a bigger opengl texture than the client memory, and different pitches
328 * SFLAG_DIBSECTION: Dibsections may have read / write protections on the memory. Avoid issues...
329 * SFLAG_OVERSIZE: The gl texture is smaller than the allocated memory
330 * SFLAG_CONVERTED: The conversion destination memory is freed after loading the surface
331 * allocatedMemory == NULL: Not defined in the extension. Seems to disable client storage effectively
333 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
334 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
335 This->Flags &= ~SFLAG_CLIENT;
336 enable_client_storage = TRUE;
337 } else {
338 This->Flags |= SFLAG_CLIENT;
340 /* Point opengl to our allocated texture memory. Do not use resource.allocatedMemory here because
341 * it might point into a pbo. Instead use heapMemory, but get the alignment right.
343 mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
346 glTexImage2D(This->glDescription.target, This->glDescription.level, internal, width, height, 0, format, type, mem);
347 checkGLcall("glTexImage2D");
349 if(enable_client_storage) {
350 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
351 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
353 LEAVE_GL();
355 This->Flags |= SFLAG_ALLOCATED;
358 /* In D3D the depth stencil dimensions have to be greater than or equal to the
359 * render target dimensions. With FBOs, the dimensions have to be an exact match. */
360 /* TODO: We should synchronize the renderbuffer's content with the texture's content. */
361 void surface_set_compatible_renderbuffer(IWineD3DSurface *iface, unsigned int width, unsigned int height) {
362 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
363 renderbuffer_entry_t *entry;
364 GLuint renderbuffer = 0;
365 unsigned int src_width, src_height;
367 src_width = This->pow2Width;
368 src_height = This->pow2Height;
370 /* A depth stencil smaller than the render target is not valid */
371 if (width > src_width || height > src_height) return;
373 /* Remove any renderbuffer set if the sizes match */
374 if (width == src_width && height == src_height) {
375 This->current_renderbuffer = NULL;
376 return;
379 /* Look if we've already got a renderbuffer of the correct dimensions */
380 LIST_FOR_EACH_ENTRY(entry, &This->renderbuffers, renderbuffer_entry_t, entry) {
381 if (entry->width == width && entry->height == height) {
382 renderbuffer = entry->id;
383 This->current_renderbuffer = entry;
384 break;
388 if (!renderbuffer) {
389 const GlPixelFormatDesc *glDesc;
390 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
392 GL_EXTCALL(glGenRenderbuffersEXT(1, &renderbuffer));
393 GL_EXTCALL(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, renderbuffer));
394 GL_EXTCALL(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, glDesc->glFormat, width, height));
396 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(renderbuffer_entry_t));
397 entry->width = width;
398 entry->height = height;
399 entry->id = renderbuffer;
400 list_add_head(&This->renderbuffers, &entry->entry);
402 This->current_renderbuffer = entry;
405 checkGLcall("set_compatible_renderbuffer");
408 GLenum surface_get_gl_buffer(IWineD3DSurface *iface, IWineD3DSwapChain *swapchain) {
409 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
410 IWineD3DSwapChainImpl *swapchain_impl = (IWineD3DSwapChainImpl *)swapchain;
412 TRACE("(%p) : swapchain %p\n", This, swapchain);
414 if (swapchain_impl->backBuffer && swapchain_impl->backBuffer[0] == iface) {
415 TRACE("Returning GL_BACK\n");
416 return GL_BACK;
417 } else if (swapchain_impl->frontBuffer == iface) {
418 TRACE("Returning GL_FRONT\n");
419 return GL_FRONT;
422 FIXME("Higher back buffer, returning GL_BACK\n");
423 return GL_BACK;
426 ULONG WINAPI IWineD3DSurfaceImpl_Release(IWineD3DSurface *iface) {
427 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
428 ULONG ref = InterlockedDecrement(&This->resource.ref);
429 TRACE("(%p) : Releasing from %d\n", This, ref + 1);
430 if (ref == 0) {
431 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
432 renderbuffer_entry_t *entry, *entry2;
433 TRACE("(%p) : cleaning up\n", This);
435 /* Need a context to destroy the texture. Use the currently active render target, but only if
436 * the primary render target exists. Otherwise lastActiveRenderTarget is garbage, see above.
437 * When destroying the primary rt, Uninit3D will activate a context before doing anything
439 if(device->render_targets && device->render_targets[0]) {
440 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
443 ENTER_GL();
444 if (This->glDescription.textureName != 0) { /* release the openGL texture.. */
445 TRACE("Deleting texture %d\n", This->glDescription.textureName);
446 glDeleteTextures(1, &This->glDescription.textureName);
449 if(This->Flags & SFLAG_PBO) {
450 /* Delete the PBO */
451 GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
454 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
455 GL_EXTCALL(glDeleteRenderbuffersEXT(1, &entry->id));
456 HeapFree(GetProcessHeap(), 0, entry);
458 LEAVE_GL();
460 if(This->Flags & SFLAG_DIBSECTION) {
461 /* Release the DC */
462 SelectObject(This->hDC, This->dib.holdbitmap);
463 DeleteDC(This->hDC);
464 /* Release the DIB section */
465 DeleteObject(This->dib.DIBsection);
466 This->dib.bitmap_data = NULL;
467 This->resource.allocatedMemory = NULL;
469 if(This->Flags & SFLAG_USERPTR) IWineD3DSurface_SetMem(iface, NULL);
471 HeapFree(GetProcessHeap(), 0, This->palette9);
473 IWineD3DResourceImpl_CleanUp((IWineD3DResource *)iface);
475 if(This->overlay_dest) {
476 list_remove(&This->overlay_entry);
479 TRACE("(%p) Released\n", This);
480 HeapFree(GetProcessHeap(), 0, This);
483 return ref;
486 /* ****************************************************
487 IWineD3DSurface IWineD3DResource parts follow
488 **************************************************** */
490 void WINAPI IWineD3DSurfaceImpl_PreLoad(IWineD3DSurface *iface) {
491 /* TODO: check for locks */
492 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
493 IWineD3DBaseTexture *baseTexture = NULL;
494 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
496 TRACE("(%p)Checking to see if the container is a base texture\n", This);
497 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
498 TRACE("Passing to container\n");
499 IWineD3DBaseTexture_PreLoad(baseTexture);
500 IWineD3DBaseTexture_Release(baseTexture);
501 } else {
502 TRACE("(%p) : About to load surface\n", This);
504 if(!device->isInDraw) {
505 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
508 if (This->resource.format == WINED3DFMT_P8 || This->resource.format == WINED3DFMT_A8P8) {
509 if(palette9_changed(This)) {
510 TRACE("Reloading surface because the d3d8/9 palette was changed\n");
511 /* TODO: This is not necessarily needed with hw palettized texture support */
512 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
513 /* Make sure the texture is reloaded because of the palette change, this kills performance though :( */
514 IWineD3DSurface_ModifyLocation(iface, SFLAG_INTEXTURE, FALSE);
518 IWineD3DSurface_LoadTexture(iface, FALSE);
520 if (This->resource.pool == WINED3DPOOL_DEFAULT) {
521 /* Tell opengl to try and keep this texture in video ram (well mostly) */
522 GLclampf tmp;
523 tmp = 0.9f;
524 ENTER_GL();
525 glPrioritizeTextures(1, &This->glDescription.textureName, &tmp);
526 LEAVE_GL();
529 return;
532 static void surface_remove_pbo(IWineD3DSurfaceImpl *This) {
533 This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
534 This->resource.allocatedMemory =
535 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
537 ENTER_GL();
538 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
539 checkGLcall("glBindBuffer(GL_PIXEL_UNPACK_BUFFER, This->pbo)");
540 GL_EXTCALL(glGetBufferSubDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0, This->resource.size, This->resource.allocatedMemory));
541 checkGLcall("glGetBufferSubData");
542 GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
543 checkGLcall("glDeleteBuffers");
544 LEAVE_GL();
546 This->pbo = 0;
547 This->Flags &= ~SFLAG_PBO;
550 static void WINAPI IWineD3DSurfaceImpl_UnLoad(IWineD3DSurface *iface) {
551 IWineD3DBaseTexture *texture = NULL;
552 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
553 renderbuffer_entry_t *entry, *entry2;
554 TRACE("(%p)\n", iface);
556 if(This->resource.pool == WINED3DPOOL_DEFAULT) {
557 /* Default pool resources are supposed to be destroyed before Reset is called.
558 * Implicit resources stay however. So this means we have an implicit render target
559 * or depth stencil. The content may be destroyed, but we still have to tear down
560 * opengl resources, so we cannot leave early.
562 * Put the most up to date surface location into the drawable. D3D-wise this content
563 * is undefined, so it would be nowhere, but that would make the location management
564 * more complicated. The drawable is a sane location, because if we mark sysmem or
565 * texture up to date, drawPrim will copy the uninitialized texture or sysmem to the
566 * uninitialized drawable. That's pointless and we'd have to allocate the texture /
567 * sysmem copy here.
569 if (This->resource.usage & WINED3DUSAGE_DEPTHSTENCIL) {
570 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
571 } else {
572 IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, TRUE);
574 } else {
575 /* Load the surface into system memory */
576 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
577 IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, FALSE);
579 IWineD3DSurface_ModifyLocation(iface, SFLAG_INTEXTURE, FALSE);
580 This->Flags &= ~SFLAG_ALLOCATED;
582 /* Destroy PBOs, but load them into real sysmem before */
583 if(This->Flags & SFLAG_PBO) {
584 surface_remove_pbo(This);
587 /* Destroy fbo render buffers. This is needed for implicit render targets, for
588 * all application-created targets the application has to release the surface
589 * before calling _Reset
591 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
592 ENTER_GL();
593 GL_EXTCALL(glDeleteRenderbuffersEXT(1, &entry->id));
594 LEAVE_GL();
595 list_remove(&entry->entry);
596 HeapFree(GetProcessHeap(), 0, entry);
598 list_init(&This->renderbuffers);
599 This->current_renderbuffer = NULL;
601 /* If we're in a texture, the texture name belongs to the texture. Otherwise,
602 * destroy it
604 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **) &texture);
605 if(!texture) {
606 ENTER_GL();
607 glDeleteTextures(1, &This->glDescription.textureName);
608 This->glDescription.textureName = 0;
609 LEAVE_GL();
610 } else {
611 IWineD3DBaseTexture_Release(texture);
613 return;
616 /* ******************************************************
617 IWineD3DSurface IWineD3DSurface parts follow
618 ****************************************************** */
620 void WINAPI IWineD3DSurfaceImpl_SetGlTextureDesc(IWineD3DSurface *iface, UINT textureName, int target) {
621 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
622 TRACE("(%p) : setting textureName %u, target %i\n", This, textureName, target);
623 if (This->glDescription.textureName == 0 && textureName != 0) {
624 IWineD3DSurface_ModifyLocation(iface, SFLAG_INTEXTURE, FALSE);
625 if((This->Flags & SFLAG_LOCATIONS) == 0) {
626 /* In 1.0-rc4 and earlier, AddDirtyRect was called in the place of this if condition.
627 * This had the problem that a correctly set INDRAWABLE flag was removed if the PreLoad
628 * during the offscreen rendering readback triggered the creation of the GL texture.
629 * The change intended to keep the INDRAWABLE intact. To prevent unintended side effects
630 * before release, set the INSYSMEM flag like the old AddDirtyRect did.
632 WARN("Wine 1.0 safety path hit\n");
633 This->Flags |= SFLAG_INSYSMEM;
636 if(target == GL_TEXTURE_RECTANGLE_ARB && This->glDescription.target != target) {
637 This->Flags &= ~SFLAG_NORMCOORD;
638 } else if(This->glDescription.target == GL_TEXTURE_RECTANGLE_ARB && target != GL_TEXTURE_RECTANGLE_ARB) {
639 This->Flags |= SFLAG_NORMCOORD;
641 This->glDescription.textureName = textureName;
642 This->glDescription.target = target;
643 This->Flags &= ~SFLAG_ALLOCATED;
646 void WINAPI IWineD3DSurfaceImpl_GetGlDesc(IWineD3DSurface *iface, glDescriptor **glDescription) {
647 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
648 TRACE("(%p) : returning %p\n", This, &This->glDescription);
649 *glDescription = &This->glDescription;
652 /* TODO: think about moving this down to resource? */
653 const void *WINAPI IWineD3DSurfaceImpl_GetData(IWineD3DSurface *iface) {
654 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
655 /* 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 */
656 if (This->resource.pool != WINED3DPOOL_SYSTEMMEM) {
657 FIXME(" (%p)Attempting to get system memory for a non-system memory texture\n", iface);
659 return (CONST void*)(This->resource.allocatedMemory);
662 /* Read the framebuffer back into the surface */
663 static void read_from_framebuffer(IWineD3DSurfaceImpl *This, CONST RECT *rect, void *dest, UINT pitch) {
664 IWineD3DSwapChainImpl *swapchain;
665 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
666 BYTE *mem;
667 GLint fmt;
668 GLint type;
669 BYTE *row, *top, *bottom;
670 int i;
671 BOOL bpp;
672 RECT local_rect;
673 BOOL srcIsUpsideDown;
675 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
676 static BOOL warned = FALSE;
677 if(!warned) {
678 ERR("The application tries to lock the render target, but render target locking is disabled\n");
679 warned = TRUE;
681 return;
684 IWineD3DSurface_GetContainer((IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&swapchain);
685 /* Activate the surface. Set it up for blitting now, although not necessarily needed for LockRect.
686 * Certain graphics drivers seem to dislike some enabled states when reading from opengl, the blitting usage
687 * should help here. Furthermore unlockrect will need the context set up for blitting. The context manager will find
688 * context->last_was_blit set on the unlock.
690 ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
691 ENTER_GL();
693 /* Select the correct read buffer, and give some debug output.
694 * There is no need to keep track of the current read buffer or reset it, every part of the code
695 * that reads sets the read buffer as desired.
697 if(!swapchain) {
698 /* Locking the primary render target which is not on a swapchain(=offscreen render target).
699 * Read from the back buffer
701 TRACE("Locking offscreen render target\n");
702 glReadBuffer(myDevice->offscreenBuffer);
703 srcIsUpsideDown = TRUE;
704 } else {
705 GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *) This, (IWineD3DSwapChain *)swapchain);
706 TRACE("Locking %#x buffer\n", buffer);
707 glReadBuffer(buffer);
708 checkGLcall("glReadBuffer");
710 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
711 srcIsUpsideDown = FALSE;
714 /* TODO: Get rid of the extra rectangle comparison and construction of a full surface rectangle */
715 if(!rect) {
716 local_rect.left = 0;
717 local_rect.top = 0;
718 local_rect.right = This->currentDesc.Width;
719 local_rect.bottom = This->currentDesc.Height;
720 } else {
721 local_rect = *rect;
723 /* TODO: Get rid of the extra GetPitch call, LockRect does that too. Cache the pitch */
725 switch(This->resource.format)
727 case WINED3DFMT_P8:
729 if(primary_render_target_is_p8(myDevice)) {
730 /* In case of P8 render targets the index is stored in the alpha component */
731 fmt = GL_ALPHA;
732 type = GL_UNSIGNED_BYTE;
733 mem = dest;
734 bpp = This->bytesPerPixel;
735 } else {
736 /* GL can't return palettized data, so read ARGB pixels into a
737 * separate block of memory and convert them into palettized format
738 * in software. Slow, but if the app means to use palettized render
739 * targets and locks it...
741 * Use GL_RGB, GL_UNSIGNED_BYTE to read the surface for performance reasons
742 * Don't use GL_BGR as in the WINED3DFMT_R8G8B8 case, instead watch out
743 * for the color channels when palettizing the colors.
745 fmt = GL_RGB;
746 type = GL_UNSIGNED_BYTE;
747 pitch *= 3;
748 mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * 3);
749 if(!mem) {
750 ERR("Out of memory\n");
751 LEAVE_GL();
752 return;
754 bpp = This->bytesPerPixel * 3;
757 break;
759 default:
760 mem = dest;
761 fmt = This->glDescription.glFormat;
762 type = This->glDescription.glType;
763 bpp = This->bytesPerPixel;
766 if(This->Flags & SFLAG_PBO) {
767 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
768 checkGLcall("glBindBufferARB");
771 glReadPixels(local_rect.left, local_rect.top,
772 local_rect.right - local_rect.left,
773 local_rect.bottom - local_rect.top,
774 fmt, type, mem);
775 vcheckGLcall("glReadPixels");
777 if(This->Flags & SFLAG_PBO) {
778 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
779 checkGLcall("glBindBufferARB");
781 /* Check if we need to flip the image. If we need to flip use glMapBufferARB
782 * to get a pointer to it and perform the flipping in software. This is a lot
783 * faster than calling glReadPixels for each line. In case we want more speed
784 * we should rerender it flipped in a FBO and read the data back from the FBO. */
785 if(!srcIsUpsideDown) {
786 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
787 checkGLcall("glBindBufferARB");
789 mem = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
790 checkGLcall("glMapBufferARB");
794 /* TODO: Merge this with the palettization loop below for P8 targets */
795 if(!srcIsUpsideDown) {
796 UINT len, off;
797 /* glReadPixels returns the image upside down, and there is no way to prevent this.
798 Flip the lines in software */
799 len = (local_rect.right - local_rect.left) * bpp;
800 off = local_rect.left * bpp;
802 row = HeapAlloc(GetProcessHeap(), 0, len);
803 if(!row) {
804 ERR("Out of memory\n");
805 if(This->resource.format == WINED3DFMT_P8) HeapFree(GetProcessHeap(), 0, mem);
806 LEAVE_GL();
807 return;
810 top = mem + pitch * local_rect.top;
811 bottom = mem + pitch * ( local_rect.bottom - local_rect.top - 1);
812 for(i = 0; i < (local_rect.bottom - local_rect.top) / 2; i++) {
813 memcpy(row, top + off, len);
814 memcpy(top + off, bottom + off, len);
815 memcpy(bottom + off, row, len);
816 top += pitch;
817 bottom -= pitch;
819 HeapFree(GetProcessHeap(), 0, row);
821 /* Unmap the temp PBO buffer */
822 if(This->Flags & SFLAG_PBO) {
823 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
824 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
828 LEAVE_GL();
830 /* For P8 textures we need to perform an inverse palette lookup. This is done by searching for a palette
831 * index which matches the RGB value. Note this isn't guaranteed to work when there are multiple entries for
832 * the same color but we have no choice.
833 * In case of P8 render targets, the index is stored in the alpha component so no conversion is needed.
835 if((This->resource.format == WINED3DFMT_P8) && !primary_render_target_is_p8(myDevice)) {
836 PALETTEENTRY *pal = NULL;
837 DWORD width = pitch / 3;
838 int x, y, c;
840 if(This->palette) {
841 pal = This->palette->palents;
842 } else {
843 ERR("Palette is missing, cannot perform inverse palette lookup\n");
844 HeapFree(GetProcessHeap(), 0, mem);
845 return ;
848 for(y = local_rect.top; y < local_rect.bottom; y++) {
849 for(x = local_rect.left; x < local_rect.right; x++) {
850 /* start lines pixels */
851 BYTE *blue = mem + y * pitch + x * (sizeof(BYTE) * 3);
852 BYTE *green = blue + 1;
853 BYTE *red = green + 1;
855 for(c = 0; c < 256; c++) {
856 if(*red == pal[c].peRed &&
857 *green == pal[c].peGreen &&
858 *blue == pal[c].peBlue)
860 *((BYTE *) dest + y * width + x) = c;
861 break;
866 HeapFree(GetProcessHeap(), 0, mem);
870 /* Read the framebuffer contents into a texture */
871 static void read_from_framebuffer_texture(IWineD3DSurfaceImpl *This)
873 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
874 IWineD3DSwapChainImpl *swapchain;
875 int bpp;
876 GLenum format, internal, type;
877 CONVERT_TYPES convert;
878 GLint prevRead;
880 d3dfmt_get_conv(This, TRUE /* We need color keying */, TRUE /* We will use textures */, &format, &internal, &type, &convert, &bpp, This->srgb);
882 IWineD3DSurface_GetContainer((IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&swapchain);
883 /* Activate the surface to read from. In some situations it isn't the currently active target(e.g. backbuffer
884 * locking during offscreen rendering). RESOURCELOAD is ok because glCopyTexSubImage2D isn't affected by any
885 * states in the stateblock, and no driver was found yet that had bugs in that regard.
887 ActivateContext(device, (IWineD3DSurface *) This, CTXUSAGE_RESOURCELOAD);
888 surface_bind_and_dirtify(This);
889 ENTER_GL();
891 glGetIntegerv(GL_READ_BUFFER, &prevRead);
893 /* Select the correct read buffer, and give some debug output.
894 * There is no need to keep track of the current read buffer or reset it, every part of the code
895 * that reads sets the read buffer as desired.
897 if(!swapchain) {
898 /* Locking the primary render target which is not on a swapchain(=offscreen render target).
899 * Read from the back buffer
901 TRACE("Locking offscreen render target\n");
902 glReadBuffer(device->offscreenBuffer);
903 } else {
904 GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *) This, (IWineD3DSwapChain *)swapchain);
905 TRACE("Locking %#x buffer\n", buffer);
906 glReadBuffer(buffer);
907 checkGLcall("glReadBuffer");
909 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
912 if(!(This->Flags & SFLAG_ALLOCATED)) {
913 surface_allocate_surface(This, internal, This->pow2Width,
914 This->pow2Height, format, type);
917 clear_unused_channels(This);
919 /* If !SrcIsUpsideDown we should flip the surface.
920 * This can be done using glCopyTexSubImage2D but this
921 * is VERY slow, so don't do that. We should prevent
922 * this code from getting called in such cases or perhaps
923 * we can use FBOs */
925 glCopyTexSubImage2D(This->glDescription.target,
926 This->glDescription.level,
927 0, 0, 0, 0,
928 This->currentDesc.Width,
929 This->currentDesc.Height);
930 checkGLcall("glCopyTexSubImage2D");
932 glReadBuffer(prevRead);
933 vcheckGLcall("glReadBuffer");
935 LEAVE_GL();
936 TRACE("Updated target %d\n", This->glDescription.target);
939 static void surface_prepare_system_memory(IWineD3DSurfaceImpl *This) {
940 /* Performance optimization: Count how often a surface is locked, if it is locked regularly do not throw away the system memory copy.
941 * This avoids the need to download the surface from opengl all the time. The surface is still downloaded if the opengl texture is
942 * changed
944 if(!(This->Flags & SFLAG_DYNLOCK)) {
945 This->lockCount++;
946 /* MAXLOCKCOUNT is defined in wined3d_private.h */
947 if(This->lockCount > MAXLOCKCOUNT) {
948 TRACE("Surface is locked regularly, not freeing the system memory copy any more\n");
949 This->Flags |= SFLAG_DYNLOCK;
953 /* Create a PBO for dynamically locked surfaces but don't do it for converted or non-pow2 surfaces.
954 * Also don't create a PBO for systemmem surfaces.
956 if(GL_SUPPORT(ARB_PIXEL_BUFFER_OBJECT) && (This->Flags & SFLAG_DYNLOCK) && !(This->Flags & (SFLAG_PBO | SFLAG_CONVERTED | SFLAG_NONPOW2)) && (This->resource.pool != WINED3DPOOL_SYSTEMMEM)) {
957 GLenum error;
958 ENTER_GL();
960 GL_EXTCALL(glGenBuffersARB(1, &This->pbo));
961 error = glGetError();
962 if(This->pbo == 0 || error != GL_NO_ERROR) {
963 ERR("Failed to bind the PBO with error %s (%#x)\n", debug_glerror(error), error);
966 TRACE("Attaching pbo=%#x to (%p)\n", This->pbo, This);
968 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
969 checkGLcall("glBindBufferARB");
971 GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->resource.size + 4, This->resource.allocatedMemory, GL_STREAM_DRAW_ARB));
972 checkGLcall("glBufferDataARB");
974 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
975 checkGLcall("glBindBufferARB");
977 /* We don't need the system memory anymore and we can't even use it for PBOs */
978 if(!(This->Flags & SFLAG_CLIENT)) {
979 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
980 This->resource.heapMemory = NULL;
982 This->resource.allocatedMemory = NULL;
983 This->Flags |= SFLAG_PBO;
984 LEAVE_GL();
985 } else if(!(This->resource.allocatedMemory || This->Flags & SFLAG_PBO)) {
986 /* Whatever surface we have, make sure that there is memory allocated for the downloaded copy,
987 * or a pbo to map
989 if(!This->resource.heapMemory) {
990 This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
992 This->resource.allocatedMemory =
993 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
994 if(This->Flags & SFLAG_INSYSMEM) {
995 ERR("Surface without memory or pbo has SFLAG_INSYSMEM set!\n");
1000 static HRESULT WINAPI IWineD3DSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags) {
1001 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1002 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
1003 IWineD3DSwapChain *swapchain = NULL;
1005 TRACE("(%p) : rect@%p flags(%08x), output lockedRect@%p, memory@%p\n", This, pRect, Flags, pLockedRect, This->resource.allocatedMemory);
1007 /* This is also done in the base class, but we have to verify this before loading any data from
1008 * gl into the sysmem copy. The PBO may be mapped, a different rectangle locked, the discard flag
1009 * may interfere, and all other bad things may happen
1011 if (This->Flags & SFLAG_LOCKED) {
1012 WARN("Surface is already locked, returning D3DERR_INVALIDCALL\n");
1013 return WINED3DERR_INVALIDCALL;
1015 This->Flags |= SFLAG_LOCKED;
1017 if (!(This->Flags & SFLAG_LOCKABLE))
1019 TRACE("Warning: trying to lock unlockable surf@%p\n", This);
1022 if (Flags & WINED3DLOCK_DISCARD) {
1023 /* Set SFLAG_INSYSMEM, so we'll never try to download the data from the texture. */
1024 TRACE("WINED3DLOCK_DISCARD flag passed, marking local copy as up to date\n");
1025 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1026 This->Flags |= SFLAG_INSYSMEM;
1027 goto lock_end;
1030 if (This->Flags & SFLAG_INSYSMEM) {
1031 TRACE("Local copy is up to date, not downloading data\n");
1032 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1033 goto lock_end;
1036 /* Now download the surface content from opengl
1037 * Use the render target readback if the surface is on a swapchain(=onscreen render target) or the current primary target
1038 * Offscreen targets which are not active at the moment or are higher targets(FBOs) can be locked with the texture path
1040 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain);
1041 if(swapchain || iface == myDevice->render_targets[0]) {
1042 const RECT *pass_rect = pRect;
1044 /* IWineD3DSurface_LoadLocation does not check if the rectangle specifies the full surfaces
1045 * because most caller functions do not need that. So do that here
1047 if(pRect &&
1048 pRect->top == 0 &&
1049 pRect->left == 0 &&
1050 pRect->right == This->currentDesc.Width &&
1051 pRect->bottom == This->currentDesc.Height) {
1052 pass_rect = NULL;
1055 switch(wined3d_settings.rendertargetlock_mode) {
1056 case RTL_TEXDRAW:
1057 case RTL_TEXTEX:
1058 FIXME("Reading from render target with a texture isn't implemented yet, falling back to framebuffer reading\n");
1059 #if 0
1060 /* Disabled for now. LoadLocation prefers the texture over the drawable as the source. So if we copy to the
1061 * texture first, then to sysmem, we'll avoid glReadPixels and use glCopyTexImage and glGetTexImage2D instead.
1062 * This may be faster on some cards
1064 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* No partial texture copy yet */);
1065 #endif
1066 /* drop through */
1068 case RTL_AUTO:
1069 case RTL_READDRAW:
1070 case RTL_READTEX:
1071 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, pRect);
1072 break;
1074 case RTL_DISABLE:
1075 break;
1077 if(swapchain) IWineD3DSwapChain_Release(swapchain);
1079 } else if(iface == myDevice->stencilBufferTarget) {
1080 /** the depth stencil in openGL has a format of GL_FLOAT
1081 * which should be good for WINED3DFMT_D16_LOCKABLE
1082 * and WINED3DFMT_D16
1083 * it is unclear what format the stencil buffer is in except.
1084 * 'Each index is converted to fixed point...
1085 * If GL_MAP_STENCIL is GL_TRUE, indices are replaced by their
1086 * mappings in the table GL_PIXEL_MAP_S_TO_S.
1087 * glReadPixels(This->lockedRect.left,
1088 * This->lockedRect.bottom - j - 1,
1089 * This->lockedRect.right - This->lockedRect.left,
1090 * 1,
1091 * GL_DEPTH_COMPONENT,
1092 * type,
1093 * (char *)pLockedRect->pBits + (pLockedRect->Pitch * (j-This->lockedRect.top)));
1095 * Depth Stencil surfaces which are not the current depth stencil target should have their data in a
1096 * gl texture(next path), or in local memory(early return because of set SFLAG_INSYSMEM above). If
1097 * none of that is the case the problem is not in this function :-)
1098 ********************************************/
1099 FIXME("Depth stencil locking not supported yet\n");
1100 } else {
1101 /* This path is for normal surfaces, offscreen render targets and everything else that is in a gl texture */
1102 TRACE("locking an ordinary surface\n");
1103 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL /* no partial locking for textures yet */);
1106 lock_end:
1107 if(This->Flags & SFLAG_PBO) {
1108 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
1109 ENTER_GL();
1110 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1111 checkGLcall("glBindBufferARB");
1113 /* This shouldn't happen but could occur if some other function didn't handle the PBO properly */
1114 if(This->resource.allocatedMemory) {
1115 ERR("The surface already has PBO memory allocated!\n");
1118 This->resource.allocatedMemory = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1119 checkGLcall("glMapBufferARB");
1121 /* Make sure the pbo isn't set anymore in order not to break non-pbo calls */
1122 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1123 checkGLcall("glBindBufferARB");
1125 LEAVE_GL();
1128 if (Flags & (WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY)) {
1129 /* Don't dirtify */
1130 } else {
1131 IWineD3DBaseTexture *pBaseTexture;
1133 * Dirtify on lock
1134 * as seen in msdn docs
1136 IWineD3DSurface_AddDirtyRect(iface, pRect);
1138 /** Dirtify Container if needed */
1139 if (WINED3D_OK == IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&pBaseTexture) && pBaseTexture != NULL) {
1140 TRACE("Making container dirty\n");
1141 IWineD3DBaseTexture_SetDirty(pBaseTexture, TRUE);
1142 IWineD3DBaseTexture_Release(pBaseTexture);
1143 } else {
1144 TRACE("Surface is standalone, no need to dirty the container\n");
1148 return IWineD3DBaseSurfaceImpl_LockRect(iface, pLockedRect, pRect, Flags);
1151 static void flush_to_framebuffer_drawpixels(IWineD3DSurfaceImpl *This, GLenum fmt, GLenum type, UINT bpp, const BYTE *mem) {
1152 GLint prev_store;
1153 GLint prev_rasterpos[4];
1154 GLint skipBytes = 0;
1155 UINT pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This); /* target is argb, 4 byte */
1156 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
1157 IWineD3DSwapChainImpl *swapchain;
1159 /* Activate the correct context for the render target */
1160 ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
1161 ENTER_GL();
1163 IWineD3DSurface_GetContainer((IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&swapchain);
1164 if(!swapchain) {
1165 /* Primary offscreen render target */
1166 TRACE("Offscreen render target\n");
1167 glDrawBuffer(myDevice->offscreenBuffer);
1168 checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
1169 } else {
1170 GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *) This, (IWineD3DSwapChain *)swapchain);
1171 TRACE("Unlocking %#x buffer\n", buffer);
1172 glDrawBuffer(buffer);
1173 checkGLcall("glDrawBuffer");
1175 IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapchain);
1178 glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
1179 vcheckGLcall("glIntegerv");
1180 glGetIntegerv(GL_CURRENT_RASTER_POSITION, &prev_rasterpos[0]);
1181 vcheckGLcall("glIntegerv");
1182 glPixelZoom(1.0, -1.0);
1183 vcheckGLcall("glPixelZoom");
1185 /* If not fullscreen, we need to skip a number of bytes to find the next row of data */
1186 glGetIntegerv(GL_UNPACK_ROW_LENGTH, &skipBytes);
1187 glPixelStorei(GL_UNPACK_ROW_LENGTH, This->currentDesc.Width);
1189 glRasterPos3i(This->lockedRect.left, This->lockedRect.top, 1);
1190 vcheckGLcall("glRasterPos2f");
1192 /* Some drivers(radeon dri, others?) don't like exceptions during
1193 * glDrawPixels. If the surface is a DIB section, it might be in GDIMode
1194 * after ReleaseDC. Reading it will cause an exception, which x11drv will
1195 * catch to put the dib section in InSync mode, which leads to a crash
1196 * and a blocked x server on my radeon card.
1198 * The following lines read the dib section so it is put in InSync mode
1199 * before glDrawPixels is called and the crash is prevented. There won't
1200 * be any interfering gdi accesses, because UnlockRect is called from
1201 * ReleaseDC, and the app won't use the dc any more afterwards.
1203 if((This->Flags & SFLAG_DIBSECTION) && !(This->Flags & SFLAG_PBO)) {
1204 volatile BYTE read;
1205 read = This->resource.allocatedMemory[0];
1208 if(This->Flags & SFLAG_PBO) {
1209 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1210 checkGLcall("glBindBufferARB");
1213 /* When the surface is locked we only have to refresh the locked part else we need to update the whole image */
1214 if(This->Flags & SFLAG_LOCKED) {
1215 glDrawPixels(This->lockedRect.right - This->lockedRect.left,
1216 (This->lockedRect.bottom - This->lockedRect.top)-1,
1217 fmt, type,
1218 mem + bpp * This->lockedRect.left + pitch * This->lockedRect.top);
1219 checkGLcall("glDrawPixels");
1220 } else {
1221 glDrawPixels(This->currentDesc.Width,
1222 This->currentDesc.Height,
1223 fmt, type, mem);
1224 checkGLcall("glDrawPixels");
1227 if(This->Flags & SFLAG_PBO) {
1228 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1229 checkGLcall("glBindBufferARB");
1232 glPixelZoom(1.0,1.0);
1233 vcheckGLcall("glPixelZoom");
1235 glRasterPos3iv(&prev_rasterpos[0]);
1236 vcheckGLcall("glRasterPos3iv");
1238 /* Reset to previous pack row length */
1239 glPixelStorei(GL_UNPACK_ROW_LENGTH, skipBytes);
1240 vcheckGLcall("glPixelStorei GL_UNPACK_ROW_LENGTH");
1242 if(!swapchain) {
1243 glDrawBuffer(myDevice->offscreenBuffer);
1244 checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
1245 } else if(swapchain->backBuffer) {
1246 glDrawBuffer(GL_BACK);
1247 checkGLcall("glDrawBuffer(GL_BACK)");
1248 } else {
1249 glDrawBuffer(GL_FRONT);
1250 checkGLcall("glDrawBuffer(GL_FRONT)");
1252 LEAVE_GL();
1254 return;
1257 static HRESULT WINAPI IWineD3DSurfaceImpl_UnlockRect(IWineD3DSurface *iface) {
1258 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1259 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
1260 IWineD3DSwapChainImpl *swapchain = NULL;
1261 BOOL fullsurface;
1263 if (!(This->Flags & SFLAG_LOCKED)) {
1264 WARN("trying to Unlock an unlocked surf@%p\n", This);
1265 return WINED3DERR_INVALIDCALL;
1268 if (This->Flags & SFLAG_PBO) {
1269 TRACE("Freeing PBO memory\n");
1270 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
1271 ENTER_GL();
1272 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1273 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1274 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1275 checkGLcall("glUnmapBufferARB");
1276 LEAVE_GL();
1277 This->resource.allocatedMemory = NULL;
1280 TRACE("(%p) : dirtyfied(%d)\n", This, This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
1282 if (This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE)) {
1283 TRACE("(%p) : Not Dirtified so nothing to do, return now\n", This);
1284 goto unlock_end;
1287 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain);
1288 if(swapchain || (myDevice->render_targets && iface == myDevice->render_targets[0])) {
1289 if(swapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
1291 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1292 static BOOL warned = FALSE;
1293 if(!warned) {
1294 ERR("The application tries to write to the render target, but render target locking is disabled\n");
1295 warned = TRUE;
1297 goto unlock_end;
1300 if(This->dirtyRect.left == 0 &&
1301 This->dirtyRect.top == 0 &&
1302 This->dirtyRect.right == This->currentDesc.Width &&
1303 This->dirtyRect.bottom == This->currentDesc.Height) {
1304 fullsurface = TRUE;
1305 } else {
1306 /* TODO: Proper partial rectangle tracking */
1307 fullsurface = FALSE;
1308 This->Flags |= SFLAG_INSYSMEM;
1311 switch(wined3d_settings.rendertargetlock_mode) {
1312 case RTL_READTEX:
1313 case RTL_TEXTEX:
1314 ActivateContext(myDevice, iface, CTXUSAGE_BLIT);
1315 ENTER_GL();
1316 if (This->glDescription.textureName == 0) {
1317 glGenTextures(1, &This->glDescription.textureName);
1318 checkGLcall("glGenTextures");
1320 glBindTexture(This->glDescription.target, This->glDescription.textureName);
1321 checkGLcall("glBindTexture(This->glDescription.target, This->glDescription.textureName)");
1322 LEAVE_GL();
1323 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* partial texture loading not supported yet */);
1324 /* drop through */
1326 case RTL_AUTO:
1327 case RTL_READDRAW:
1328 case RTL_TEXDRAW:
1329 IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, fullsurface ? NULL : &This->dirtyRect);
1330 break;
1333 if(!fullsurface) {
1334 /* Partial rectangle tracking is not commonly implemented, it is only done for render targets. Overwrite
1335 * the flags to bring them back into a sane state. INSYSMEM was set before to tell LoadLocation where
1336 * to read the rectangle from. Indrawable is set because all modifications from the partial sysmem copy
1337 * are written back to the drawable, thus the surface is merged again in the drawable. The sysmem copy is
1338 * not fully up to date because only a subrectangle was read in LockRect.
1340 This->Flags &= ~SFLAG_INSYSMEM;
1341 This->Flags |= SFLAG_INDRAWABLE;
1344 This->dirtyRect.left = This->currentDesc.Width;
1345 This->dirtyRect.top = This->currentDesc.Height;
1346 This->dirtyRect.right = 0;
1347 This->dirtyRect.bottom = 0;
1348 } else if(iface == myDevice->stencilBufferTarget) {
1349 FIXME("Depth Stencil buffer locking is not implemented\n");
1350 } else {
1351 /* The rest should be a normal texture */
1352 IWineD3DBaseTextureImpl *impl;
1353 /* Check if the texture is bound, if yes dirtify the sampler to force a re-upload of the texture
1354 * Can't load the texture here because PreLoad may destroy and recreate the gl texture, so sampler
1355 * states need resetting
1357 if(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&impl) == WINED3D_OK) {
1358 if(impl->baseTexture.bindCount) {
1359 IWineD3DDeviceImpl_MarkStateDirty(myDevice, STATE_SAMPLER(impl->baseTexture.sampler));
1361 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *) impl);
1365 unlock_end:
1366 This->Flags &= ~SFLAG_LOCKED;
1367 memset(&This->lockedRect, 0, sizeof(RECT));
1369 /* Overlays have to be redrawn manually after changes with the GL implementation */
1370 if(This->overlay_dest) {
1371 IWineD3DSurface_DrawOverlay(iface);
1373 return WINED3D_OK;
1376 HRESULT WINAPI IWineD3DSurfaceImpl_GetDC(IWineD3DSurface *iface, HDC *pHDC) {
1377 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1378 WINED3DLOCKED_RECT lock;
1379 HRESULT hr;
1380 RGBQUAD col[256];
1382 TRACE("(%p)->(%p)\n",This,pHDC);
1384 if(This->Flags & SFLAG_USERPTR) {
1385 ERR("Not supported on surfaces with an application-provided surfaces\n");
1386 return WINEDDERR_NODC;
1389 /* Give more detailed info for ddraw */
1390 if (This->Flags & SFLAG_DCINUSE)
1391 return WINEDDERR_DCALREADYCREATED;
1393 /* Can't GetDC if the surface is locked */
1394 if (This->Flags & SFLAG_LOCKED)
1395 return WINED3DERR_INVALIDCALL;
1397 /* According to Direct3D9 docs, only these formats are supported */
1398 if (((IWineD3DImpl *)This->resource.wineD3DDevice->wineD3D)->dxVersion > 7) {
1399 if (This->resource.format != WINED3DFMT_R5G6B5 &&
1400 This->resource.format != WINED3DFMT_X1R5G5B5 &&
1401 This->resource.format != WINED3DFMT_R8G8B8 &&
1402 This->resource.format != WINED3DFMT_X8R8G8B8) return WINED3DERR_INVALIDCALL;
1405 memset(&lock, 0, sizeof(lock)); /* To be sure */
1407 /* Create a DIB section if there isn't a hdc yet */
1408 if(!This->hDC) {
1409 IWineD3DBaseSurfaceImpl_CreateDIBSection(iface);
1410 if(This->Flags & SFLAG_CLIENT) {
1411 IWineD3DSurface_PreLoad(iface);
1414 /* Use the dib section from now on if we are not using a PBO */
1415 if(!(This->Flags & SFLAG_PBO))
1416 This->resource.allocatedMemory = This->dib.bitmap_data;
1419 /* Lock the surface */
1420 hr = IWineD3DSurface_LockRect(iface,
1421 &lock,
1422 NULL,
1425 if(This->Flags & SFLAG_PBO) {
1426 /* Sync the DIB with the PBO. This can't be done earlier because LockRect activates the allocatedMemory */
1427 memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, This->dib.bitmap_size);
1430 if(FAILED(hr)) {
1431 ERR("IWineD3DSurface_LockRect failed with hr = %08x\n", hr);
1432 /* keep the dib section */
1433 return hr;
1436 if(This->resource.format == WINED3DFMT_P8 ||
1437 This->resource.format == WINED3DFMT_A8P8) {
1438 /* GetDC on palettized formats is unsupported in D3D9, and the method is missing in
1439 D3D8, so this should only be used for DX <=7 surfaces (with non-device palettes) */
1440 unsigned int n;
1441 PALETTEENTRY *pal = NULL;
1443 if(This->palette) {
1444 pal = This->palette->palents;
1445 } else {
1446 IWineD3DSurfaceImpl *dds_primary;
1447 IWineD3DSwapChainImpl *swapchain;
1448 swapchain = (IWineD3DSwapChainImpl *)This->resource.wineD3DDevice->swapchains[0];
1449 dds_primary = (IWineD3DSurfaceImpl *)swapchain->frontBuffer;
1450 if (dds_primary && dds_primary->palette)
1451 pal = dds_primary->palette->palents;
1454 if (pal) {
1455 for (n=0; n<256; n++) {
1456 col[n].rgbRed = pal[n].peRed;
1457 col[n].rgbGreen = pal[n].peGreen;
1458 col[n].rgbBlue = pal[n].peBlue;
1459 col[n].rgbReserved = 0;
1461 SetDIBColorTable(This->hDC, 0, 256, col);
1465 *pHDC = This->hDC;
1466 TRACE("returning %p\n",*pHDC);
1467 This->Flags |= SFLAG_DCINUSE;
1469 return WINED3D_OK;
1472 HRESULT WINAPI IWineD3DSurfaceImpl_ReleaseDC(IWineD3DSurface *iface, HDC hDC) {
1473 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1475 TRACE("(%p)->(%p)\n",This,hDC);
1477 if (!(This->Flags & SFLAG_DCINUSE))
1478 return WINED3DERR_INVALIDCALL;
1480 if (This->hDC !=hDC) {
1481 WARN("Application tries to release an invalid DC(%p), surface dc is %p\n", hDC, This->hDC);
1482 return WINED3DERR_INVALIDCALL;
1485 if((This->Flags & SFLAG_PBO) && This->resource.allocatedMemory) {
1486 /* Copy the contents of the DIB over to the PBO */
1487 memcpy(This->resource.allocatedMemory, This->dib.bitmap_data, This->dib.bitmap_size);
1490 /* we locked first, so unlock now */
1491 IWineD3DSurface_UnlockRect(iface);
1493 This->Flags &= ~SFLAG_DCINUSE;
1495 return WINED3D_OK;
1498 /* ******************************************************
1499 IWineD3DSurface Internal (No mapping to directx api) parts follow
1500 ****************************************************** */
1502 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) {
1503 BOOL colorkey_active = need_alpha_ck && (This->CKeyFlags & WINEDDSD_CKSRCBLT);
1504 const GlPixelFormatDesc *glDesc;
1505 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1506 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
1508 /* Default values: From the surface */
1509 *format = glDesc->glFormat;
1510 *type = glDesc->glType;
1511 *convert = NO_CONVERSION;
1512 *target_bpp = This->bytesPerPixel;
1514 if(srgb_mode) {
1515 *internal = glDesc->glGammaInternal;
1516 } else if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
1517 *internal = glDesc->rtInternal;
1518 } else {
1519 *internal = glDesc->glInternal;
1522 /* Ok, now look if we have to do any conversion */
1523 switch(This->resource.format) {
1524 case WINED3DFMT_P8:
1525 /* ****************
1526 Paletted Texture
1527 **************** */
1529 /* Use conversion when the paletted texture extension OR fragment shaders are available. When either
1530 * of the two is available make sure texturing is requested as neither of the two works in
1531 * conjunction with calls like glDraw-/glReadPixels. Further also use conversion in case of color keying.
1532 * Paletted textures can be emulated using shaders but only do that for 2D purposes e.g. situations
1533 * in which the main render target uses p8. Some games like GTA Vice City use P8 for texturing which
1534 * conflicts with this.
1536 if( !(GL_SUPPORT(EXT_PALETTED_TEXTURE) || (GL_SUPPORT(ARB_FRAGMENT_PROGRAM) && primary_render_target_is_p8(device))) || colorkey_active || !use_texturing ) {
1537 *format = GL_RGBA;
1538 *internal = GL_RGBA;
1539 *type = GL_UNSIGNED_BYTE;
1540 *target_bpp = 4;
1541 if(colorkey_active) {
1542 *convert = CONVERT_PALETTED_CK;
1543 } else {
1544 *convert = CONVERT_PALETTED;
1547 else if(!GL_SUPPORT(EXT_PALETTED_TEXTURE) && GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
1548 *format = GL_ALPHA;
1549 *internal = GL_RGBA;
1550 *type = GL_UNSIGNED_BYTE;
1551 *target_bpp = 1;
1554 break;
1556 case WINED3DFMT_R3G3B2:
1557 /* **********************
1558 GL_UNSIGNED_BYTE_3_3_2
1559 ********************** */
1560 if (colorkey_active) {
1561 /* This texture format will never be used.. So do not care about color keying
1562 up until the point in time it will be needed :-) */
1563 FIXME(" ColorKeying not supported in the RGB 332 format !\n");
1565 break;
1567 case WINED3DFMT_R5G6B5:
1568 if (colorkey_active) {
1569 *convert = CONVERT_CK_565;
1570 *format = GL_RGBA;
1571 *internal = GL_RGBA;
1572 *type = GL_UNSIGNED_SHORT_5_5_5_1;
1574 break;
1576 case WINED3DFMT_X1R5G5B5:
1577 if (colorkey_active) {
1578 *convert = CONVERT_CK_5551;
1579 *format = GL_BGRA;
1580 *internal = GL_RGBA;
1581 *type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
1583 break;
1585 case WINED3DFMT_R8G8B8:
1586 if (colorkey_active) {
1587 *convert = CONVERT_CK_RGB24;
1588 *format = GL_RGBA;
1589 *internal = GL_RGBA;
1590 *type = GL_UNSIGNED_INT_8_8_8_8;
1591 *target_bpp = 4;
1593 break;
1595 case WINED3DFMT_X8R8G8B8:
1596 if (colorkey_active) {
1597 *convert = CONVERT_RGB32_888;
1598 *format = GL_RGBA;
1599 *internal = GL_RGBA;
1600 *type = GL_UNSIGNED_INT_8_8_8_8;
1602 break;
1604 case WINED3DFMT_V8U8:
1605 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1606 else if(GL_SUPPORT(ATI_ENVMAP_BUMPMAP)) {
1607 *format = GL_DUDV_ATI;
1608 *internal = GL_DU8DV8_ATI;
1609 *type = GL_BYTE;
1610 /* No conversion - Just change the gl type */
1611 break;
1613 *convert = CONVERT_V8U8;
1614 *format = GL_BGR;
1615 *internal = GL_RGB8;
1616 *type = GL_UNSIGNED_BYTE;
1617 *target_bpp = 3;
1618 break;
1620 case WINED3DFMT_L6V5U5:
1621 *convert = CONVERT_L6V5U5;
1622 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1623 *target_bpp = 3;
1624 /* Use format and types from table */
1625 } else {
1626 /* Load it into unsigned R5G6B5, swap L and V channels, and revert that in the shader */
1627 *target_bpp = 2;
1628 *format = GL_RGB;
1629 *internal = GL_RGB5;
1630 *type = GL_UNSIGNED_SHORT_5_6_5;
1632 break;
1634 case WINED3DFMT_X8L8V8U8:
1635 *convert = CONVERT_X8L8V8U8;
1636 *target_bpp = 4;
1637 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1638 /* Use formats from gl table. It is a bit unfortunate, but the conversion
1639 * is needed to set the X format to 255 to get 1.0 for alpha when sampling
1640 * the texture. OpenGL can't use GL_DSDT8_MAG8_NV as internal format with
1641 * the needed type and format parameter, so the internal format contains a
1642 * 4th component, which is returned as alpha
1644 } else {
1645 /* Not supported by GL_ATI_envmap_bumpmap */
1646 *format = GL_BGRA;
1647 *internal = GL_RGB8;
1648 *type = GL_UNSIGNED_INT_8_8_8_8_REV;
1650 break;
1652 case WINED3DFMT_Q8W8V8U8:
1653 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1654 *convert = CONVERT_Q8W8V8U8;
1655 *format = GL_BGRA;
1656 *internal = GL_RGBA8;
1657 *type = GL_UNSIGNED_BYTE;
1658 *target_bpp = 4;
1659 /* Not supported by GL_ATI_envmap_bumpmap */
1660 break;
1662 case WINED3DFMT_V16U16:
1663 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1664 *convert = CONVERT_V16U16;
1665 *format = GL_BGR;
1666 *internal = GL_RGB16_EXT;
1667 *type = GL_UNSIGNED_SHORT;
1668 *target_bpp = 6;
1669 /* What should I do here about GL_ATI_envmap_bumpmap?
1670 * Convert it or allow data loss by loading it into a 8 bit / channel texture?
1672 break;
1674 case WINED3DFMT_A4L4:
1675 /* A4L4 exists as an internal gl format, but for some reason there is not
1676 * format+type combination to load it. Thus convert it to A8L8, then load it
1677 * with A4L4 internal, but A8L8 format+type
1679 *convert = CONVERT_A4L4;
1680 *format = GL_LUMINANCE_ALPHA;
1681 *internal = GL_LUMINANCE4_ALPHA4;
1682 *type = GL_UNSIGNED_BYTE;
1683 *target_bpp = 2;
1684 break;
1686 case WINED3DFMT_R32F:
1687 /* Can be loaded in theory with fmt=GL_RED, type=GL_FLOAT, but this fails. The reason
1688 * is that D3D expects the undefined green, blue and alpha channels to return 1.0
1689 * when sampling, but OpenGL sets green and blue to 0.0 instead. Thus we have to inject
1690 * 1.0 instead.
1692 * The alpha channel defaults to 1.0 in opengl, so nothing has to be done about it.
1694 *convert = CONVERT_R32F;
1695 *format = GL_RGB;
1696 *internal = GL_RGB32F_ARB;
1697 *type = GL_FLOAT;
1698 *target_bpp = 12;
1699 break;
1701 case WINED3DFMT_R16F:
1702 /* Similar to R32F */
1703 *convert = CONVERT_R16F;
1704 *format = GL_RGB;
1705 *internal = GL_RGB16F_ARB;
1706 *type = GL_HALF_FLOAT_ARB;
1707 *target_bpp = 6;
1708 break;
1710 case WINED3DFMT_G16R16:
1711 *convert = CONVERT_G16R16;
1712 *format = GL_RGB;
1713 *internal = GL_RGB16_EXT;
1714 *type = GL_UNSIGNED_SHORT;
1715 *target_bpp = 6;
1716 break;
1718 default:
1719 break;
1722 return WINED3D_OK;
1725 HRESULT d3dfmt_convert_surface(BYTE *src, BYTE *dst, UINT pitch, UINT width, UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *This) {
1726 BYTE *source, *dest;
1727 TRACE("(%p)->(%p),(%d,%d,%d,%d,%p)\n", src, dst, pitch, height, outpitch, convert,This);
1729 switch (convert) {
1730 case NO_CONVERSION:
1732 memcpy(dst, src, pitch * height);
1733 break;
1735 case CONVERT_PALETTED:
1736 case CONVERT_PALETTED_CK:
1738 IWineD3DPaletteImpl* pal = This->palette;
1739 BYTE table[256][4];
1740 unsigned int x, y;
1742 if( pal == NULL) {
1743 /* TODO: If we are a sublevel, try to get the palette from level 0 */
1746 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
1748 for (y = 0; y < height; y++)
1750 source = src + pitch * y;
1751 dest = dst + outpitch * y;
1752 /* This is an 1 bpp format, using the width here is fine */
1753 for (x = 0; x < width; x++) {
1754 BYTE color = *source++;
1755 *dest++ = table[color][0];
1756 *dest++ = table[color][1];
1757 *dest++ = table[color][2];
1758 *dest++ = table[color][3];
1762 break;
1764 case CONVERT_CK_565:
1766 /* Converting the 565 format in 5551 packed to emulate color-keying.
1768 Note : in all these conversion, it would be best to average the averaging
1769 pixels to get the color of the pixel that will be color-keyed to
1770 prevent 'color bleeding'. This will be done later on if ever it is
1771 too visible.
1773 Note2: Nvidia documents say that their driver does not support alpha + color keying
1774 on the same surface and disables color keying in such a case
1776 unsigned int x, y;
1777 WORD *Source;
1778 WORD *Dest;
1780 TRACE("Color keyed 565\n");
1782 for (y = 0; y < height; y++) {
1783 Source = (WORD *) (src + y * pitch);
1784 Dest = (WORD *) (dst + y * outpitch);
1785 for (x = 0; x < width; x++ ) {
1786 WORD color = *Source++;
1787 *Dest = ((color & 0xFFC0) | ((color & 0x1F) << 1));
1788 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1789 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1790 *Dest |= 0x0001;
1792 Dest++;
1796 break;
1798 case CONVERT_CK_5551:
1800 /* Converting X1R5G5B5 format to R5G5B5A1 to emulate color-keying. */
1801 unsigned int x, y;
1802 WORD *Source;
1803 WORD *Dest;
1804 TRACE("Color keyed 5551\n");
1805 for (y = 0; y < height; y++) {
1806 Source = (WORD *) (src + y * pitch);
1807 Dest = (WORD *) (dst + y * outpitch);
1808 for (x = 0; x < width; x++ ) {
1809 WORD color = *Source++;
1810 *Dest = color;
1811 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1812 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1813 *Dest |= (1 << 15);
1815 else {
1816 *Dest &= ~(1 << 15);
1818 Dest++;
1822 break;
1824 case CONVERT_RGB32_888:
1826 /* Converting X8R8G8B8 format to R8G8B8A8 with color-keying. */
1827 unsigned int x, y;
1828 for (y = 0; y < height; y++)
1830 source = src + pitch * y;
1831 dest = dst + outpitch * y;
1832 for (x = 0; x < width; x++) {
1833 DWORD color = 0xffffff & *(DWORD*)source;
1834 DWORD dstcolor = color << 8;
1835 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1836 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1837 dstcolor |= 0xff;
1839 *(DWORD*)dest = dstcolor;
1840 source += 4;
1841 dest += 4;
1845 break;
1847 case CONVERT_V8U8:
1849 unsigned int x, y;
1850 short *Source;
1851 unsigned char *Dest;
1852 for(y = 0; y < height; y++) {
1853 Source = (short *) (src + y * pitch);
1854 Dest = dst + y * outpitch;
1855 for (x = 0; x < width; x++ ) {
1856 long color = (*Source++);
1857 /* B */ Dest[0] = 0xff;
1858 /* G */ Dest[1] = (color >> 8) + 128; /* V */
1859 /* R */ Dest[2] = (color) + 128; /* U */
1860 Dest += 3;
1863 break;
1866 case CONVERT_V16U16:
1868 unsigned int x, y;
1869 DWORD *Source;
1870 unsigned short *Dest;
1871 for(y = 0; y < height; y++) {
1872 Source = (DWORD *) (src + y * pitch);
1873 Dest = (unsigned short *) (dst + y * outpitch);
1874 for (x = 0; x < width; x++ ) {
1875 DWORD color = (*Source++);
1876 /* B */ Dest[0] = 0xffff;
1877 /* G */ Dest[1] = (color >> 16) + 32768; /* V */
1878 /* R */ Dest[2] = (color ) + 32768; /* U */
1879 Dest += 3;
1882 break;
1885 case CONVERT_Q8W8V8U8:
1887 unsigned int x, y;
1888 DWORD *Source;
1889 unsigned char *Dest;
1890 for(y = 0; y < height; y++) {
1891 Source = (DWORD *) (src + y * pitch);
1892 Dest = dst + y * outpitch;
1893 for (x = 0; x < width; x++ ) {
1894 long color = (*Source++);
1895 /* B */ Dest[0] = ((color >> 16) & 0xff) + 128; /* W */
1896 /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
1897 /* R */ Dest[2] = (color & 0xff) + 128; /* U */
1898 /* A */ Dest[3] = ((color >> 24) & 0xff) + 128; /* Q */
1899 Dest += 4;
1902 break;
1905 case CONVERT_L6V5U5:
1907 unsigned int x, y;
1908 WORD *Source;
1909 unsigned char *Dest;
1911 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1912 /* This makes the gl surface bigger(24 bit instead of 16), but it works with
1913 * fixed function and shaders without further conversion once the surface is
1914 * loaded
1916 for(y = 0; y < height; y++) {
1917 Source = (WORD *) (src + y * pitch);
1918 Dest = dst + y * outpitch;
1919 for (x = 0; x < width; x++ ) {
1920 short color = (*Source++);
1921 unsigned char l = ((color >> 10) & 0xfc);
1922 char v = ((color >> 5) & 0x3e);
1923 char u = ((color ) & 0x1f);
1925 /* 8 bits destination, 6 bits source, 8th bit is the sign. gl ignores the sign
1926 * and doubles the positive range. Thus shift left only once, gl does the 2nd
1927 * shift. GL reads a signed value and converts it into an unsigned value.
1929 /* M */ Dest[2] = l << 1;
1931 /* Those are read as signed, but kept signed. Just left-shift 3 times to scale
1932 * from 5 bit values to 8 bit values.
1934 /* V */ Dest[1] = v << 3;
1935 /* U */ Dest[0] = u << 3;
1936 Dest += 3;
1939 } else {
1940 for(y = 0; y < height; y++) {
1941 unsigned short *Dest_s = (unsigned short *) (dst + y * outpitch);
1942 Source = (WORD *) (src + y * pitch);
1943 for (x = 0; x < width; x++ ) {
1944 short color = (*Source++);
1945 unsigned char l = ((color >> 10) & 0xfc);
1946 short v = ((color >> 5) & 0x3e);
1947 short u = ((color ) & 0x1f);
1948 short v_conv = v + 16;
1949 short u_conv = u + 16;
1951 *Dest_s = ((v_conv << 11) & 0xf800) | ((l << 5) & 0x7e0) | (u_conv & 0x1f);
1952 Dest_s += 1;
1956 break;
1959 case CONVERT_X8L8V8U8:
1961 unsigned int x, y;
1962 DWORD *Source;
1963 unsigned char *Dest;
1965 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1966 /* This implementation works with the fixed function pipeline and shaders
1967 * without further modification after converting the surface.
1969 for(y = 0; y < height; y++) {
1970 Source = (DWORD *) (src + y * pitch);
1971 Dest = dst + y * outpitch;
1972 for (x = 0; x < width; x++ ) {
1973 long color = (*Source++);
1974 /* L */ Dest[2] = ((color >> 16) & 0xff); /* L */
1975 /* V */ Dest[1] = ((color >> 8 ) & 0xff); /* V */
1976 /* U */ Dest[0] = (color & 0xff); /* U */
1977 /* I */ Dest[3] = 255; /* X */
1978 Dest += 4;
1981 } else {
1982 /* Doesn't work correctly with the fixed function pipeline, but can work in
1983 * shaders if the shader is adjusted. (There's no use for this format in gl's
1984 * standard fixed function pipeline anyway).
1986 for(y = 0; y < height; y++) {
1987 Source = (DWORD *) (src + y * pitch);
1988 Dest = dst + y * outpitch;
1989 for (x = 0; x < width; x++ ) {
1990 long color = (*Source++);
1991 /* B */ Dest[0] = ((color >> 16) & 0xff); /* L */
1992 /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
1993 /* R */ Dest[2] = (color & 0xff) + 128; /* U */
1994 Dest += 4;
1998 break;
2001 case CONVERT_A4L4:
2003 unsigned int x, y;
2004 unsigned char *Source;
2005 unsigned char *Dest;
2006 for(y = 0; y < height; y++) {
2007 Source = src + y * pitch;
2008 Dest = dst + y * outpitch;
2009 for (x = 0; x < width; x++ ) {
2010 unsigned char color = (*Source++);
2011 /* A */ Dest[1] = (color & 0xf0) << 0;
2012 /* L */ Dest[0] = (color & 0x0f) << 4;
2013 Dest += 2;
2016 break;
2019 case CONVERT_R32F:
2021 unsigned int x, y;
2022 float *Source;
2023 float *Dest;
2024 for(y = 0; y < height; y++) {
2025 Source = (float *) (src + y * pitch);
2026 Dest = (float *) (dst + y * outpitch);
2027 for (x = 0; x < width; x++ ) {
2028 float color = (*Source++);
2029 Dest[0] = color;
2030 Dest[1] = 1.0;
2031 Dest[2] = 1.0;
2032 Dest += 3;
2035 break;
2038 case CONVERT_R16F:
2040 unsigned int x, y;
2041 WORD *Source;
2042 WORD *Dest;
2043 WORD one = 0x3c00;
2044 for(y = 0; y < height; y++) {
2045 Source = (WORD *) (src + y * pitch);
2046 Dest = (WORD *) (dst + y * outpitch);
2047 for (x = 0; x < width; x++ ) {
2048 WORD color = (*Source++);
2049 Dest[0] = color;
2050 Dest[1] = one;
2051 Dest[2] = one;
2052 Dest += 3;
2055 break;
2058 case CONVERT_G16R16:
2060 unsigned int x, y;
2061 WORD *Source;
2062 WORD *Dest;
2064 for(y = 0; y < height; y++) {
2065 Source = (WORD *) (src + y * pitch);
2066 Dest = (WORD *) (dst + y * outpitch);
2067 for (x = 0; x < width; x++ ) {
2068 WORD green = (*Source++);
2069 WORD red = (*Source++);
2070 Dest[0] = green;
2071 Dest[1] = red;
2072 Dest[2] = 0xffff;
2073 Dest += 3;
2076 break;
2079 default:
2080 ERR("Unsupported conversation type %d\n", convert);
2082 return WINED3D_OK;
2085 static void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey) {
2086 IWineD3DPaletteImpl* pal = This->palette;
2087 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2088 BOOL index_in_alpha = FALSE;
2089 int dxVersion = ( (IWineD3DImpl *) device->wineD3D)->dxVersion;
2090 int i;
2092 /* Old games like StarCraft, C&C, Red Alert and others use P8 render targets.
2093 * Reading back the RGB output each lockrect (each frame as they lock the whole screen)
2094 * is slow. Further RGB->P8 conversion is not possible because palettes can have
2095 * duplicate entries. Store the color key in the unused alpha component to speed the
2096 * download up and to make conversion unneeded. */
2097 index_in_alpha = primary_render_target_is_p8(device);
2099 if (pal == NULL) {
2100 /* In DirectDraw the palette is a property of the surface, there are no such things as device palettes. */
2101 if(dxVersion <= 7) {
2102 ERR("This code should never get entered for DirectDraw!, expect problems\n");
2103 if(index_in_alpha) {
2104 /* Guarantees that memory representation remains correct after sysmem<->texture transfers even if
2105 there's no palette at this time. */
2106 for (i = 0; i < 256; i++) table[i][3] = i;
2108 } else {
2109 /* Direct3D >= 8 palette usage style: P8 textures use device palettes, palette entry format is A8R8G8B8,
2110 alpha is stored in peFlags and may be used by the app if D3DPTEXTURECAPS_ALPHAPALETTE device
2111 capability flag is present (wine does advertise this capability) */
2112 for (i = 0; i < 256; i++) {
2113 table[i][0] = device->palettes[device->currentPalette][i].peRed;
2114 table[i][1] = device->palettes[device->currentPalette][i].peGreen;
2115 table[i][2] = device->palettes[device->currentPalette][i].peBlue;
2116 table[i][3] = device->palettes[device->currentPalette][i].peFlags;
2119 } else {
2120 TRACE("Using surface palette %p\n", pal);
2121 /* Get the surface's palette */
2122 for (i = 0; i < 256; i++) {
2123 table[i][0] = pal->palents[i].peRed;
2124 table[i][1] = pal->palents[i].peGreen;
2125 table[i][2] = pal->palents[i].peBlue;
2127 /* When index_in_alpha is the palette index is stored in the alpha component. In case of a readback
2128 we can then read GL_ALPHA. Color keying is handled in BltOverride using a GL_ALPHA_TEST using GL_NOT_EQUAL.
2129 In case of index_in_alpha the color key itself is passed to glAlphaFunc in other cases the alpha component
2130 of pixels that should be masked away is set to 0. */
2131 if(index_in_alpha) {
2132 table[i][3] = i;
2133 } else if(colorkey && (i >= This->SrcBltCKey.dwColorSpaceLowValue) && (i <= This->SrcBltCKey.dwColorSpaceHighValue)) {
2134 table[i][3] = 0x00;
2135 } else if(pal->Flags & WINEDDPCAPS_ALPHA) {
2136 table[i][3] = pal->palents[i].peFlags;
2137 } else {
2138 table[i][3] = 0xFF;
2144 const char *fragment_palette_conversion =
2145 "!!ARBfp1.0\n"
2146 "TEMP index;\n"
2147 "PARAM constants = { 0.996, 0.00195, 0, 0 };\n" /* { 255/256, 0.5/255*255/256, 0, 0 } */
2148 "TEX index, fragment.texcoord[0], texture[0], 2D;\n" /* The alpha-component contains the palette index */
2149 "MAD index.a, index.a, 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 */
2150 "TEX result.color, index.a, texture[1], 1D;\n" /* use the alpha-component as a index in the palette to get the final color */
2151 "END";
2153 /* This function is used in case of 8bit paletted textures to upload the palette.
2154 It supports GL_EXT_paletted_texture and GL_ARB_fragment_program, support for other
2155 extensions like ATI_fragment_shaders is possible.
2157 static void d3dfmt_p8_upload_palette(IWineD3DSurface *iface, CONVERT_TYPES convert) {
2158 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2159 BYTE table[256][4];
2160 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2162 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
2164 /* Try to use the paletted texture extension */
2165 if(GL_SUPPORT(EXT_PALETTED_TEXTURE))
2167 TRACE("Using GL_EXT_PALETTED_TEXTURE for 8-bit paletted texture support\n");
2168 GL_EXTCALL(glColorTableEXT(This->glDescription.target,GL_RGBA,256,GL_RGBA,GL_UNSIGNED_BYTE, table));
2170 else
2172 /* Let a fragment shader do the color conversion by uploading the palette to a 1D texture.
2173 * The 8bit pixel data will be used as an index in this palette texture to retrieve the final color. */
2174 TRACE("Using fragment shaders for emulating 8-bit paletted texture support\n");
2176 /* Create the fragment program if we don't have it */
2177 if(!device->paletteConversionShader)
2179 glEnable(GL_FRAGMENT_PROGRAM_ARB);
2180 GL_EXTCALL(glGenProgramsARB(1, &device->paletteConversionShader));
2181 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, device->paletteConversionShader));
2182 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(fragment_palette_conversion), (const GLbyte *)fragment_palette_conversion));
2183 glDisable(GL_FRAGMENT_PROGRAM_ARB);
2186 glEnable(GL_FRAGMENT_PROGRAM_ARB);
2187 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, device->paletteConversionShader));
2189 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE1));
2190 glEnable(GL_TEXTURE_1D);
2191 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2193 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2194 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); /* Make sure we have discrete color levels. */
2195 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2196 glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, table); /* Upload the palette */
2198 /* Switch back to unit 0 in which the 2D texture will be stored. */
2199 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0));
2201 /* Rebind the texture because it isn't bound anymore */
2202 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2206 BOOL palette9_changed(IWineD3DSurfaceImpl *This) {
2207 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2209 if(This->palette || (This->resource.format != WINED3DFMT_P8 && This->resource.format != WINED3DFMT_A8P8)) {
2210 /* If a ddraw-style palette is attached assume no d3d9 palette change.
2211 * Also the palette isn't interesting if the surface format isn't P8 or A8P8
2213 return FALSE;
2216 if(This->palette9) {
2217 if(memcmp(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256) == 0) {
2218 return FALSE;
2220 } else {
2221 This->palette9 = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
2223 memcpy(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256);
2224 return TRUE;
2227 static inline void clear_unused_channels(IWineD3DSurfaceImpl *This) {
2228 GLboolean oldwrite[4];
2230 /* Some formats have only some color channels, and the others are 1.0.
2231 * since our rendering renders to all channels, and those pixel formats
2232 * are emulated by using a full texture with the other channels set to 1.0
2233 * manually, clear the unused channels.
2235 * This could be done with hacking colorwriteenable to mask the colors,
2236 * but before drawing the buffer would have to be cleared too, so there's
2237 * no gain in that
2239 switch(This->resource.format) {
2240 case WINED3DFMT_R16F:
2241 case WINED3DFMT_R32F:
2242 TRACE("R16F or R32F format, clearing green, blue and alpha to 1.0\n");
2243 /* Do not activate a context, the correct drawable is active already
2244 * though just the read buffer is set, make sure to have the correct draw
2245 * buffer too
2247 glDrawBuffer(This->resource.wineD3DDevice->offscreenBuffer);
2248 glDisable(GL_SCISSOR_TEST);
2249 glGetBooleanv(GL_COLOR_WRITEMASK, oldwrite);
2250 glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_TRUE);
2251 glClearColor(0.0, 1.0, 1.0, 1.0);
2252 glClear(GL_COLOR_BUFFER_BIT);
2253 glColorMask(oldwrite[0], oldwrite[1], oldwrite[2], oldwrite[3]);
2254 if(!This->resource.wineD3DDevice->render_offscreen) glDrawBuffer(GL_BACK);
2255 checkGLcall("Unused channel clear\n");
2256 break;
2258 default: break;
2262 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadTexture(IWineD3DSurface *iface, BOOL srgb_mode) {
2263 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2265 if (!(This->Flags & SFLAG_INTEXTURE)) {
2266 TRACE("Reloading because surface is dirty\n");
2267 } else if(/* Reload: gl texture has ck, now no ckey is set OR */
2268 ((This->Flags & SFLAG_GLCKEY) && (!(This->CKeyFlags & WINEDDSD_CKSRCBLT))) ||
2269 /* Reload: vice versa OR */
2270 ((!(This->Flags & SFLAG_GLCKEY)) && (This->CKeyFlags & WINEDDSD_CKSRCBLT)) ||
2271 /* Also reload: Color key is active AND the color key has changed */
2272 ((This->CKeyFlags & WINEDDSD_CKSRCBLT) && (
2273 (This->glCKey.dwColorSpaceLowValue != This->SrcBltCKey.dwColorSpaceLowValue) ||
2274 (This->glCKey.dwColorSpaceHighValue != This->SrcBltCKey.dwColorSpaceHighValue)))) {
2275 TRACE("Reloading because of color keying\n");
2276 /* To perform the color key conversion we need a sysmem copy of
2277 * the surface. Make sure we have it
2280 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
2281 /* Make sure the texture is reloaded because of the color key change, this kills performance though :( */
2282 /* TODO: This is not necessarily needed with hw palettized texture support */
2283 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2284 } else {
2285 TRACE("surface is already in texture\n");
2286 return WINED3D_OK;
2289 /* Resources are placed in system RAM and do not need to be recreated when a device is lost.
2290 * These resources are not bound by device size or format restrictions. Because of this,
2291 * these resources cannot be accessed by the Direct3D device nor set as textures or render targets.
2292 * However, these resources can always be created, locked, and copied.
2294 if (This->resource.pool == WINED3DPOOL_SCRATCH )
2296 FIXME("(%p) Operation not supported for scratch textures\n",This);
2297 return WINED3DERR_INVALIDCALL;
2300 This->srgb = srgb_mode;
2301 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* no partial locking for textures yet */);
2303 #if 0
2305 static unsigned int gen = 0;
2306 char buffer[4096];
2307 ++gen;
2308 if ((gen % 10) == 0) {
2309 snprintf(buffer, sizeof(buffer), "/tmp/surface%p_type%u_level%u_%u.ppm", This, This->glDescription.target, This->glDescription.level, gen);
2310 IWineD3DSurfaceImpl_SaveSnapshot(iface, buffer);
2313 * debugging crash code
2314 if (gen == 250) {
2315 void** test = NULL;
2316 *test = 0;
2320 #endif
2322 if (!(This->Flags & SFLAG_DONOTFREE)) {
2323 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
2324 This->resource.allocatedMemory = NULL;
2325 This->resource.heapMemory = NULL;
2326 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, FALSE);
2329 return WINED3D_OK;
2332 static void WINAPI IWineD3DSurfaceImpl_BindTexture(IWineD3DSurface *iface) {
2333 /* TODO: check for locks */
2334 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2335 IWineD3DBaseTexture *baseTexture = NULL;
2336 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2338 TRACE("(%p)Checking to see if the container is a base texture\n", This);
2339 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
2340 TRACE("Passing to container\n");
2341 IWineD3DBaseTexture_BindTexture(baseTexture);
2342 IWineD3DBaseTexture_Release(baseTexture);
2343 } else {
2344 TRACE("(%p) : Binding surface\n", This);
2346 if(!device->isInDraw) {
2347 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
2350 ENTER_GL();
2352 glEnable(This->glDescription.target);
2354 if (!This->glDescription.level) {
2355 if (!This->glDescription.textureName) {
2356 glGenTextures(1, &This->glDescription.textureName);
2357 checkGLcall("glGenTextures");
2358 TRACE("Surface %p given name %d\n", This, This->glDescription.textureName);
2360 /* This is where we should be reducing the amount of GLMemoryUsed */
2361 } else if (This->glDescription.textureName) {
2362 /* Mipmap surfaces should have a base texture container */
2363 ERR("Mipmap surface has a glTexture bound to it!\n");
2366 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2367 checkGLcall("glBindTexture");
2369 LEAVE_GL();
2371 return;
2374 #include <errno.h>
2375 #include <stdio.h>
2376 HRESULT WINAPI IWineD3DSurfaceImpl_SaveSnapshot(IWineD3DSurface *iface, const char* filename) {
2377 FILE* f = NULL;
2378 UINT i, y;
2379 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2380 char *allocatedMemory;
2381 char *textureRow;
2382 IWineD3DSwapChain *swapChain = NULL;
2383 int width, height;
2384 GLuint tmpTexture = 0;
2385 DWORD color;
2386 /*FIXME:
2387 Textures may not be stored in ->allocatedgMemory and a GlTexture
2388 so we should lock the surface before saving a snapshot, or at least check that
2390 /* TODO: Compressed texture images can be obtained from the GL in uncompressed form
2391 by calling GetTexImage and in compressed form by calling
2392 GetCompressedTexImageARB. Queried compressed images can be saved and
2393 later reused by calling CompressedTexImage[123]DARB. Pre-compressed
2394 texture images do not need to be processed by the GL and should
2395 significantly improve texture loading performance relative to uncompressed
2396 images. */
2398 /* Setup the width and height to be the internal texture width and height. */
2399 width = This->pow2Width;
2400 height = This->pow2Height;
2401 /* check to see if we're a 'virtual' texture, e.g. we're not a pbuffer of texture, we're a back buffer*/
2402 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapChain);
2404 if (This->Flags & SFLAG_INDRAWABLE && !(This->Flags & SFLAG_INTEXTURE)) {
2405 /* if were not a real texture then read the back buffer into a real texture */
2406 /* we don't want to interfere with the back buffer so read the data into a temporary
2407 * texture and then save the data out of the temporary texture
2409 GLint prevRead;
2410 ENTER_GL();
2411 TRACE("(%p) Reading render target into texture\n", This);
2412 glEnable(GL_TEXTURE_2D);
2414 glGenTextures(1, &tmpTexture);
2415 glBindTexture(GL_TEXTURE_2D, tmpTexture);
2417 glTexImage2D(GL_TEXTURE_2D,
2419 GL_RGBA,
2420 width,
2421 height,
2422 0/*border*/,
2423 GL_RGBA,
2424 GL_UNSIGNED_INT_8_8_8_8_REV,
2425 NULL);
2427 glGetIntegerv(GL_READ_BUFFER, &prevRead);
2428 vcheckGLcall("glGetIntegerv");
2429 glReadBuffer(swapChain ? GL_BACK : This->resource.wineD3DDevice->offscreenBuffer);
2430 vcheckGLcall("glReadBuffer");
2431 glCopyTexImage2D(GL_TEXTURE_2D,
2433 GL_RGBA,
2436 width,
2437 height,
2440 checkGLcall("glCopyTexImage2D");
2441 glReadBuffer(prevRead);
2442 LEAVE_GL();
2444 } else { /* bind the real texture, and make sure it up to date */
2445 IWineD3DSurface_PreLoad(iface);
2447 allocatedMemory = HeapAlloc(GetProcessHeap(), 0, width * height * 4);
2448 ENTER_GL();
2449 FIXME("Saving texture level %d width %d height %d\n", This->glDescription.level, width, height);
2450 glGetTexImage(GL_TEXTURE_2D,
2451 This->glDescription.level,
2452 GL_RGBA,
2453 GL_UNSIGNED_INT_8_8_8_8_REV,
2454 allocatedMemory);
2455 checkGLcall("glTexImage2D");
2456 if (tmpTexture) {
2457 glBindTexture(GL_TEXTURE_2D, 0);
2458 glDeleteTextures(1, &tmpTexture);
2460 LEAVE_GL();
2462 f = fopen(filename, "w+");
2463 if (NULL == f) {
2464 ERR("opening of %s failed with: %s\n", filename, strerror(errno));
2465 return WINED3DERR_INVALIDCALL;
2467 /* Save the data out to a TGA file because 1: it's an easy raw format, 2: it supports an alpha channel */
2468 TRACE("(%p) opened %s with format %s\n", This, filename, debug_d3dformat(This->resource.format));
2469 /* TGA header */
2470 fputc(0,f);
2471 fputc(0,f);
2472 fputc(2,f);
2473 fputc(0,f);
2474 fputc(0,f);
2475 fputc(0,f);
2476 fputc(0,f);
2477 fputc(0,f);
2478 fputc(0,f);
2479 fputc(0,f);
2480 fputc(0,f);
2481 fputc(0,f);
2482 /* short width*/
2483 fwrite(&width,2,1,f);
2484 /* short height */
2485 fwrite(&height,2,1,f);
2486 /* format rgba */
2487 fputc(0x20,f);
2488 fputc(0x28,f);
2489 /* raw data */
2490 /* 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 */
2491 if(swapChain)
2492 textureRow = allocatedMemory + (width * (height - 1) *4);
2493 else
2494 textureRow = allocatedMemory;
2495 for (y = 0 ; y < height; y++) {
2496 for (i = 0; i < width; i++) {
2497 color = *((DWORD*)textureRow);
2498 fputc((color >> 16) & 0xFF, f); /* B */
2499 fputc((color >> 8) & 0xFF, f); /* G */
2500 fputc((color >> 0) & 0xFF, f); /* R */
2501 fputc((color >> 24) & 0xFF, f); /* A */
2502 textureRow += 4;
2504 /* take two rows of the pointer to the texture memory */
2505 if(swapChain)
2506 (textureRow-= width << 3);
2509 TRACE("Closing file\n");
2510 fclose(f);
2512 if(swapChain) {
2513 IWineD3DSwapChain_Release(swapChain);
2515 HeapFree(GetProcessHeap(), 0, allocatedMemory);
2516 return WINED3D_OK;
2520 * Slightly inefficient way to handle multiple dirty rects but it works :)
2522 HRESULT WINAPI IWineD3DSurfaceImpl_AddDirtyRect(IWineD3DSurface *iface, CONST RECT* pDirtyRect) {
2523 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2524 IWineD3DBaseTexture *baseTexture = NULL;
2526 if (!(This->Flags & SFLAG_INSYSMEM) && (This->Flags & SFLAG_INTEXTURE))
2527 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL /* no partial locking for textures yet */);
2529 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2530 if (NULL != pDirtyRect) {
2531 This->dirtyRect.left = min(This->dirtyRect.left, pDirtyRect->left);
2532 This->dirtyRect.top = min(This->dirtyRect.top, pDirtyRect->top);
2533 This->dirtyRect.right = max(This->dirtyRect.right, pDirtyRect->right);
2534 This->dirtyRect.bottom = max(This->dirtyRect.bottom, pDirtyRect->bottom);
2535 } else {
2536 This->dirtyRect.left = 0;
2537 This->dirtyRect.top = 0;
2538 This->dirtyRect.right = This->currentDesc.Width;
2539 This->dirtyRect.bottom = This->currentDesc.Height;
2541 TRACE("(%p) : Dirty: yes, Rect:(%d,%d,%d,%d)\n", This, This->dirtyRect.left,
2542 This->dirtyRect.top, This->dirtyRect.right, This->dirtyRect.bottom);
2543 /* if the container is a basetexture then mark it dirty. */
2544 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
2545 TRACE("Passing to container\n");
2546 IWineD3DBaseTexture_SetDirty(baseTexture, TRUE);
2547 IWineD3DBaseTexture_Release(baseTexture);
2549 return WINED3D_OK;
2552 HRESULT WINAPI IWineD3DSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format) {
2553 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2554 HRESULT hr;
2555 const GlPixelFormatDesc *glDesc;
2556 getFormatDescEntry(format, &GLINFO_LOCATION, &glDesc);
2558 TRACE("(%p) : Calling base function first\n", This);
2559 hr = IWineD3DBaseSurfaceImpl_SetFormat(iface, format);
2560 if(SUCCEEDED(hr)) {
2561 /* Setup some glformat defaults */
2562 This->glDescription.glFormat = glDesc->glFormat;
2563 This->glDescription.glFormatInternal = glDesc->glInternal;
2564 This->glDescription.glType = glDesc->glType;
2566 This->Flags &= ~SFLAG_ALLOCATED;
2567 TRACE("(%p) : glFormat %d, glFotmatInternal %d, glType %d\n", This,
2568 This->glDescription.glFormat, This->glDescription.glFormatInternal, This->glDescription.glType);
2570 return hr;
2573 HRESULT WINAPI IWineD3DSurfaceImpl_SetMem(IWineD3DSurface *iface, void *Mem) {
2574 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
2576 if(This->Flags & (SFLAG_LOCKED | SFLAG_DCINUSE)) {
2577 WARN("Surface is locked or the HDC is in use\n");
2578 return WINED3DERR_INVALIDCALL;
2581 if(Mem && Mem != This->resource.allocatedMemory) {
2582 void *release = NULL;
2584 /* Do I have to copy the old surface content? */
2585 if(This->Flags & SFLAG_DIBSECTION) {
2586 /* Release the DC. No need to hold the critical section for the update
2587 * Thread because this thread runs only on front buffers, but this method
2588 * fails for render targets in the check above.
2590 SelectObject(This->hDC, This->dib.holdbitmap);
2591 DeleteDC(This->hDC);
2592 /* Release the DIB section */
2593 DeleteObject(This->dib.DIBsection);
2594 This->dib.bitmap_data = NULL;
2595 This->resource.allocatedMemory = NULL;
2596 This->hDC = NULL;
2597 This->Flags &= ~SFLAG_DIBSECTION;
2598 } else if(!(This->Flags & SFLAG_USERPTR)) {
2599 release = This->resource.heapMemory;
2600 This->resource.heapMemory = NULL;
2602 This->resource.allocatedMemory = Mem;
2603 This->Flags |= SFLAG_USERPTR | SFLAG_INSYSMEM;
2605 /* Now the surface memory is most up do date. Invalidate drawable and texture */
2606 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2608 /* For client textures opengl has to be notified */
2609 if(This->Flags & SFLAG_CLIENT) {
2610 This->Flags &= ~SFLAG_ALLOCATED;
2611 IWineD3DSurface_PreLoad(iface);
2612 /* And hope that the app behaves correctly and did not free the old surface memory before setting a new pointer */
2615 /* Now free the old memory if any */
2616 HeapFree(GetProcessHeap(), 0, release);
2617 } else if(This->Flags & SFLAG_USERPTR) {
2618 /* LockRect and GetDC will re-create the dib section and allocated memory */
2619 This->resource.allocatedMemory = NULL;
2620 /* HeapMemory should be NULL already */
2621 if(This->resource.heapMemory != NULL) ERR("User pointer surface has heap memory allocated\n");
2622 This->Flags &= ~SFLAG_USERPTR;
2624 if(This->Flags & SFLAG_CLIENT) {
2625 This->Flags &= ~SFLAG_ALLOCATED;
2626 /* This respecifies an empty texture and opengl knows that the old memory is gone */
2627 IWineD3DSurface_PreLoad(iface);
2630 return WINED3D_OK;
2633 void flip_surface(IWineD3DSurfaceImpl *front, IWineD3DSurfaceImpl *back) {
2635 /* Flip the surface contents */
2636 /* Flip the DC */
2638 HDC tmp;
2639 tmp = front->hDC;
2640 front->hDC = back->hDC;
2641 back->hDC = tmp;
2644 /* Flip the DIBsection */
2646 HBITMAP tmp;
2647 BOOL hasDib = front->Flags & SFLAG_DIBSECTION;
2648 tmp = front->dib.DIBsection;
2649 front->dib.DIBsection = back->dib.DIBsection;
2650 back->dib.DIBsection = tmp;
2652 if(back->Flags & SFLAG_DIBSECTION) front->Flags |= SFLAG_DIBSECTION;
2653 else front->Flags &= ~SFLAG_DIBSECTION;
2654 if(hasDib) back->Flags |= SFLAG_DIBSECTION;
2655 else back->Flags &= ~SFLAG_DIBSECTION;
2658 /* Flip the surface data */
2660 void* tmp;
2662 tmp = front->dib.bitmap_data;
2663 front->dib.bitmap_data = back->dib.bitmap_data;
2664 back->dib.bitmap_data = tmp;
2666 tmp = front->resource.allocatedMemory;
2667 front->resource.allocatedMemory = back->resource.allocatedMemory;
2668 back->resource.allocatedMemory = tmp;
2670 tmp = front->resource.heapMemory;
2671 front->resource.heapMemory = back->resource.heapMemory;
2672 back->resource.heapMemory = tmp;
2675 /* Flip the PBO */
2677 GLuint tmp_pbo = front->pbo;
2678 front->pbo = back->pbo;
2679 back->pbo = tmp_pbo;
2682 /* client_memory should not be different, but just in case */
2684 BOOL tmp;
2685 tmp = front->dib.client_memory;
2686 front->dib.client_memory = back->dib.client_memory;
2687 back->dib.client_memory = tmp;
2690 /* Flip the opengl texture */
2692 glDescriptor tmp_desc = back->glDescription;
2693 back->glDescription = front->glDescription;
2694 front->glDescription = tmp_desc;
2698 DWORD tmp_flags = back->Flags;
2699 back->Flags = front->Flags;
2700 front->Flags = tmp_flags;
2704 static HRESULT WINAPI IWineD3DSurfaceImpl_Flip(IWineD3DSurface *iface, IWineD3DSurface *override, DWORD Flags) {
2705 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2706 IWineD3DSwapChainImpl *swapchain = NULL;
2707 HRESULT hr;
2708 TRACE("(%p)->(%p,%x)\n", This, override, Flags);
2710 /* Flipping is only supported on RenderTargets and overlays*/
2711 if( !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_OVERLAY)) ) {
2712 WARN("Tried to flip a non-render target, non-overlay surface\n");
2713 return WINEDDERR_NOTFLIPPABLE;
2716 if(This->resource.usage & WINED3DUSAGE_OVERLAY) {
2717 flip_surface(This, (IWineD3DSurfaceImpl *) override);
2719 /* Update the overlay if it is visible */
2720 if(This->overlay_dest) {
2721 return IWineD3DSurface_DrawOverlay((IWineD3DSurface *) This);
2722 } else {
2723 return WINED3D_OK;
2727 if(override) {
2728 /* DDraw sets this for the X11 surfaces, so don't confuse the user
2729 * FIXME("(%p) Target override is not supported by now\n", This);
2730 * Additionally, it isn't really possible to support triple-buffering
2731 * properly on opengl at all
2735 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **) &swapchain);
2736 if(!swapchain) {
2737 ERR("Flipped surface is not on a swapchain\n");
2738 return WINEDDERR_NOTFLIPPABLE;
2741 /* Just overwrite the swapchain presentation interval. This is ok because only ddraw apps can call Flip,
2742 * and only d3d8 and d3d9 apps specify the presentation interval
2744 if((Flags & (WINEDDFLIP_NOVSYNC | WINEDDFLIP_INTERVAL2 | WINEDDFLIP_INTERVAL3 | WINEDDFLIP_INTERVAL4)) == 0) {
2745 /* Most common case first to avoid wasting time on all the other cases */
2746 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_ONE;
2747 } else if(Flags & WINEDDFLIP_NOVSYNC) {
2748 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
2749 } else if(Flags & WINEDDFLIP_INTERVAL2) {
2750 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_TWO;
2751 } else if(Flags & WINEDDFLIP_INTERVAL3) {
2752 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_THREE;
2753 } else {
2754 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_FOUR;
2757 /* Flipping a OpenGL surface -> Use WineD3DDevice::Present */
2758 hr = IWineD3DSwapChain_Present((IWineD3DSwapChain *) swapchain, NULL, NULL, 0, NULL, 0);
2759 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
2760 return hr;
2763 /* Does a direct frame buffer -> texture copy. Stretching is done
2764 * with single pixel copy calls
2766 static inline void fb_copy_to_texture_direct(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface, IWineD3DSwapChainImpl *swapchain, WINED3DRECT *srect, WINED3DRECT *drect, BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter) {
2767 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2768 float xrel, yrel;
2769 UINT row;
2770 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2773 ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
2774 IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
2775 ENTER_GL();
2777 /* TODO: Do we need GL_TEXTURE_2D enabled fpr copyteximage? */
2778 glEnable(This->glDescription.target);
2779 checkGLcall("glEnable(This->glDescription.target)");
2781 /* Bind the target texture */
2782 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2783 checkGLcall("glBindTexture");
2784 if(!swapchain) {
2785 TRACE("Reading from an offscreen target\n");
2786 upsidedown = !upsidedown;
2787 glReadBuffer(myDevice->offscreenBuffer);
2788 } else {
2789 GLenum buffer = surface_get_gl_buffer(SrcSurface, (IWineD3DSwapChain *)swapchain);
2790 glReadBuffer(buffer);
2792 checkGLcall("glReadBuffer");
2794 xrel = (float) (srect->x2 - srect->x1) / (float) (drect->x2 - drect->x1);
2795 yrel = (float) (srect->y2 - srect->y1) / (float) (drect->y2 - drect->y1);
2797 if( (xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) {
2798 FIXME("Doing a pixel by pixel copy from the framebuffer to a texture, expect major performance issues\n");
2800 if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
2801 ERR("Texture filtering not supported in direct blit\n");
2803 } else if((Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) && ((yrel - 1.0 < -eps) || (yrel - 1.0 > eps))) {
2804 ERR("Texture filtering not supported in direct blit\n");
2807 if(upsidedown &&
2808 !((xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) &&
2809 !((yrel - 1.0 < -eps) || (yrel - 1.0 > eps))) {
2810 /* Upside down copy without stretching is nice, one glCopyTexSubImage call will do */
2812 glCopyTexSubImage2D(This->glDescription.target,
2813 This->glDescription.level,
2814 drect->x1, drect->y1, /* xoffset, yoffset */
2815 srect->x1, Src->currentDesc.Height - srect->y2,
2816 drect->x2 - drect->x1, drect->y2 - drect->y1);
2817 } else {
2818 UINT yoffset = Src->currentDesc.Height - srect->y1 + drect->y1 - 1;
2819 /* I have to process this row by row to swap the image,
2820 * otherwise it would be upside down, so stretching in y direction
2821 * doesn't cost extra time
2823 * However, stretching in x direction can be avoided if not necessary
2825 for(row = drect->y1; row < drect->y2; row++) {
2826 if( (xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) {
2827 /* Well, that stuff works, but it's very slow.
2828 * find a better way instead
2830 UINT col;
2832 for(col = drect->x1; col < drect->x2; col++) {
2833 glCopyTexSubImage2D(This->glDescription.target,
2834 This->glDescription.level,
2835 drect->x1 + col, row, /* xoffset, yoffset */
2836 srect->x1 + col * xrel, yoffset - (int) (row * yrel),
2837 1, 1);
2839 } else {
2840 glCopyTexSubImage2D(This->glDescription.target,
2841 This->glDescription.level,
2842 drect->x1, row, /* xoffset, yoffset */
2843 srect->x1, yoffset - (int) (row * yrel),
2844 drect->x2-drect->x1, 1);
2848 vcheckGLcall("glCopyTexSubImage2D");
2850 /* Leave the opengl state valid for blitting */
2851 glDisable(This->glDescription.target);
2852 checkGLcall("glDisable(This->glDescription.target)");
2854 LEAVE_GL();
2857 /* Uses the hardware to stretch and flip the image */
2858 static inline void fb_copy_to_texture_hwstretch(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface, IWineD3DSwapChainImpl *swapchain, WINED3DRECT *srect, WINED3DRECT *drect, BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter) {
2859 GLuint src, backup = 0;
2860 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2861 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2862 float left, right, top, bottom; /* Texture coordinates */
2863 UINT fbwidth = Src->currentDesc.Width;
2864 UINT fbheight = Src->currentDesc.Height;
2865 GLenum drawBuffer = GL_BACK;
2866 GLenum texture_target;
2867 BOOL noBackBufferBackup;
2869 TRACE("Using hwstretch blit\n");
2870 /* Activate the Proper context for reading from the source surface, set it up for blitting */
2871 ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
2872 IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
2874 noBackBufferBackup = !swapchain && wined3d_settings.offscreen_rendering_mode == ORM_FBO;
2875 if(!noBackBufferBackup && Src->glDescription.textureName == 0) {
2876 /* Get it a description */
2877 IWineD3DSurface_PreLoad(SrcSurface);
2879 ENTER_GL();
2881 /* Try to use an aux buffer for drawing the rectangle. This way it doesn't need restoring.
2882 * This way we don't have to wait for the 2nd readback to finish to leave this function.
2884 if(myDevice->activeContext->aux_buffers >= 2) {
2885 /* Got more than one aux buffer? Use the 2nd aux buffer */
2886 drawBuffer = GL_AUX1;
2887 } else if((swapchain || myDevice->offscreenBuffer == GL_BACK) && myDevice->activeContext->aux_buffers >= 1) {
2888 /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
2889 drawBuffer = GL_AUX0;
2892 if(noBackBufferBackup) {
2893 glGenTextures(1, &backup);
2894 checkGLcall("glGenTextures\n");
2895 glBindTexture(GL_TEXTURE_2D, backup);
2896 checkGLcall("glBindTexture(Src->glDescription.target, Src->glDescription.textureName)");
2897 texture_target = GL_TEXTURE_2D;
2898 } else {
2899 /* Backup the back buffer and copy the source buffer into a texture to draw an upside down stretched quad. If
2900 * we are reading from the back buffer, the backup can be used as source texture
2902 texture_target = Src->glDescription.target;
2903 glBindTexture(texture_target, Src->glDescription.textureName);
2904 checkGLcall("glBindTexture(texture_target, Src->glDescription.textureName)");
2905 glEnable(texture_target);
2906 checkGLcall("glEnable(texture_target)");
2908 /* For now invalidate the texture copy of the back buffer. Drawable and sysmem copy are untouched */
2909 Src->Flags &= ~SFLAG_INTEXTURE;
2912 if(swapchain) {
2913 glReadBuffer(surface_get_gl_buffer(SrcSurface, (IWineD3DSwapChain *)swapchain));
2914 } else {
2915 TRACE("Reading from an offscreen target\n");
2916 upsidedown = !upsidedown;
2917 glReadBuffer(myDevice->offscreenBuffer);
2920 /* TODO: Only back up the part that will be overwritten */
2921 glCopyTexSubImage2D(texture_target, 0,
2922 0, 0 /* read offsets */,
2923 0, 0,
2924 fbwidth,
2925 fbheight);
2927 checkGLcall("glCopyTexSubImage2D");
2929 /* No issue with overriding these - the sampler is dirty due to blit usage */
2930 glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER,
2931 magLookup[Filter - WINED3DTEXF_NONE]);
2932 checkGLcall("glTexParameteri");
2933 glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER,
2934 minMipLookup[Filter][WINED3DTEXF_NONE]);
2935 checkGLcall("glTexParameteri");
2937 if(!swapchain || (IWineD3DSurface *) Src == swapchain->backBuffer[0]) {
2938 src = backup ? backup : Src->glDescription.textureName;
2939 } else {
2940 glReadBuffer(GL_FRONT);
2941 checkGLcall("glReadBuffer(GL_FRONT)");
2943 glGenTextures(1, &src);
2944 checkGLcall("glGenTextures(1, &src)");
2945 glBindTexture(GL_TEXTURE_2D, src);
2946 checkGLcall("glBindTexture(GL_TEXTURE_2D, src)");
2948 /* TODO: Only copy the part that will be read. Use srect->x1, srect->y2 as origin, but with the width watch
2949 * out for power of 2 sizes
2951 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Src->pow2Width, Src->pow2Height, 0,
2952 GL_RGBA, GL_UNSIGNED_BYTE, NULL);
2953 checkGLcall("glTexImage2D");
2954 glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
2955 0, 0 /* read offsets */,
2956 0, 0,
2957 fbwidth,
2958 fbheight);
2960 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2961 checkGLcall("glTexParameteri");
2962 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2963 checkGLcall("glTexParameteri");
2965 glReadBuffer(GL_BACK);
2966 checkGLcall("glReadBuffer(GL_BACK)");
2968 if(texture_target != GL_TEXTURE_2D) {
2969 glDisable(texture_target);
2970 glEnable(GL_TEXTURE_2D);
2971 texture_target = GL_TEXTURE_2D;
2974 checkGLcall("glEnd and previous");
2976 left = srect->x1;
2977 right = srect->x2;
2979 if(upsidedown) {
2980 top = Src->currentDesc.Height - srect->y1;
2981 bottom = Src->currentDesc.Height - srect->y2;
2982 } else {
2983 top = Src->currentDesc.Height - srect->y2;
2984 bottom = Src->currentDesc.Height - srect->y1;
2987 if(Src->Flags & SFLAG_NORMCOORD) {
2988 left /= Src->pow2Width;
2989 right /= Src->pow2Width;
2990 top /= Src->pow2Height;
2991 bottom /= Src->pow2Height;
2994 /* draw the source texture stretched and upside down. The correct surface is bound already */
2995 glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
2996 glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
2998 glDrawBuffer(drawBuffer);
2999 glReadBuffer(drawBuffer);
3001 glBegin(GL_QUADS);
3002 /* bottom left */
3003 glTexCoord2f(left, bottom);
3004 glVertex2i(0, fbheight);
3006 /* top left */
3007 glTexCoord2f(left, top);
3008 glVertex2i(0, fbheight - drect->y2 - drect->y1);
3010 /* top right */
3011 glTexCoord2f(right, top);
3012 glVertex2i(drect->x2 - drect->x1, fbheight - drect->y2 - drect->y1);
3014 /* bottom right */
3015 glTexCoord2f(right, bottom);
3016 glVertex2i(drect->x2 - drect->x1, fbheight);
3017 glEnd();
3018 checkGLcall("glEnd and previous");
3020 if(texture_target != This->glDescription.target) {
3021 glDisable(texture_target);
3022 glEnable(This->glDescription.target);
3023 texture_target = This->glDescription.target;
3026 /* Now read the stretched and upside down image into the destination texture */
3027 glBindTexture(texture_target, This->glDescription.textureName);
3028 checkGLcall("glBindTexture");
3029 glCopyTexSubImage2D(texture_target,
3031 drect->x1, drect->y1, /* xoffset, yoffset */
3032 0, 0, /* We blitted the image to the origin */
3033 drect->x2 - drect->x1, drect->y2 - drect->y1);
3034 checkGLcall("glCopyTexSubImage2D");
3036 if(drawBuffer == GL_BACK) {
3037 /* Write the back buffer backup back */
3038 if(backup) {
3039 if(texture_target != GL_TEXTURE_2D) {
3040 glDisable(texture_target);
3041 glEnable(GL_TEXTURE_2D);
3042 texture_target = GL_TEXTURE_2D;
3044 glBindTexture(GL_TEXTURE_2D, backup);
3045 checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
3046 } else {
3047 if(texture_target != Src->glDescription.target) {
3048 glDisable(texture_target);
3049 glEnable(Src->glDescription.target);
3050 texture_target = Src->glDescription.target;
3052 glBindTexture(Src->glDescription.target, Src->glDescription.textureName);
3053 checkGLcall("glBindTexture(Src->glDescription.target, Src->glDescription.textureName)");
3056 glBegin(GL_QUADS);
3057 /* top left */
3058 glTexCoord2f(0.0, (float) fbheight / (float) Src->pow2Height);
3059 glVertex2i(0, 0);
3061 /* bottom left */
3062 glTexCoord2f(0.0, 0.0);
3063 glVertex2i(0, fbheight);
3065 /* bottom right */
3066 glTexCoord2f((float) fbwidth / (float) Src->pow2Width, 0.0);
3067 glVertex2i(fbwidth, Src->currentDesc.Height);
3069 /* top right */
3070 glTexCoord2f((float) fbwidth / (float) Src->pow2Width, (float) fbheight / (float) Src->pow2Height);
3071 glVertex2i(fbwidth, 0);
3072 glEnd();
3073 } else {
3074 /* Restore the old draw buffer */
3075 glDrawBuffer(GL_BACK);
3077 glDisable(texture_target);
3078 checkGLcall("glDisable(texture_target)");
3080 /* Cleanup */
3081 if(src != Src->glDescription.textureName && src != backup) {
3082 glDeleteTextures(1, &src);
3083 checkGLcall("glDeleteTextures(1, &src)");
3085 if(backup) {
3086 glDeleteTextures(1, &backup);
3087 checkGLcall("glDeleteTextures(1, &backup)");
3090 LEAVE_GL();
3093 /* Not called from the VTable */
3094 static HRESULT IWineD3DSurfaceImpl_BltOverride(IWineD3DSurfaceImpl *This, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
3095 WINED3DRECT rect;
3096 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3097 IWineD3DSwapChainImpl *srcSwapchain = NULL, *dstSwapchain = NULL;
3098 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
3100 TRACE("(%p)->(%p,%p,%p,%08x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3102 /* Get the swapchain. One of the surfaces has to be a primary surface */
3103 if(This->resource.pool == WINED3DPOOL_SYSTEMMEM) {
3104 WARN("Destination is in sysmem, rejecting gl blt\n");
3105 return WINED3DERR_INVALIDCALL;
3107 IWineD3DSurface_GetContainer( (IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&dstSwapchain);
3108 if(dstSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) dstSwapchain);
3109 if(Src) {
3110 if(Src->resource.pool == WINED3DPOOL_SYSTEMMEM) {
3111 WARN("Src is in sysmem, rejecting gl blt\n");
3112 return WINED3DERR_INVALIDCALL;
3114 IWineD3DSurface_GetContainer( (IWineD3DSurface *) Src, &IID_IWineD3DSwapChain, (void **)&srcSwapchain);
3115 if(srcSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) srcSwapchain);
3118 /* Early sort out of cases where no render target is used */
3119 if(!dstSwapchain && !srcSwapchain &&
3120 SrcSurface != myDevice->render_targets[0] && This != (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
3121 TRACE("No surface is render target, not using hardware blit. Src = %p, dst = %p\n", Src, This);
3122 return WINED3DERR_INVALIDCALL;
3125 /* No destination color keying supported */
3126 if(Flags & (WINEDDBLT_KEYDEST | WINEDDBLT_KEYDESTOVERRIDE)) {
3127 /* Can we support that with glBlendFunc if blitting to the frame buffer? */
3128 TRACE("Destination color key not supported in accelerated Blit, falling back to software\n");
3129 return WINED3DERR_INVALIDCALL;
3132 if (DestRect) {
3133 rect.x1 = DestRect->left;
3134 rect.y1 = DestRect->top;
3135 rect.x2 = DestRect->right;
3136 rect.y2 = DestRect->bottom;
3137 } else {
3138 rect.x1 = 0;
3139 rect.y1 = 0;
3140 rect.x2 = This->currentDesc.Width;
3141 rect.y2 = This->currentDesc.Height;
3144 /* The only case where both surfaces on a swapchain are supported is a back buffer -> front buffer blit on the same swapchain */
3145 if(dstSwapchain && dstSwapchain == srcSwapchain && dstSwapchain->backBuffer &&
3146 ((IWineD3DSurface *) This == dstSwapchain->frontBuffer) && SrcSurface == dstSwapchain->backBuffer[0]) {
3147 /* Half-life does a Blt from the back buffer to the front buffer,
3148 * Full surface size, no flags... Use present instead
3150 * This path will only be entered for d3d7 and ddraw apps, because d3d8/9 offer no way to blit TO the front buffer
3153 /* Check rects - IWineD3DDevice_Present doesn't handle them */
3154 while(1)
3156 RECT mySrcRect;
3157 TRACE("Looking if a Present can be done...\n");
3158 /* Source Rectangle must be full surface */
3159 if( SrcRect ) {
3160 if(SrcRect->left != 0 || SrcRect->top != 0 ||
3161 SrcRect->right != Src->currentDesc.Width || SrcRect->bottom != Src->currentDesc.Height) {
3162 TRACE("No, Source rectangle doesn't match\n");
3163 break;
3166 mySrcRect.left = 0;
3167 mySrcRect.top = 0;
3168 mySrcRect.right = Src->currentDesc.Width;
3169 mySrcRect.bottom = Src->currentDesc.Height;
3171 /* No stretching may occur */
3172 if(mySrcRect.right != rect.x2 - rect.x1 ||
3173 mySrcRect.bottom != rect.y2 - rect.y1) {
3174 TRACE("No, stretching is done\n");
3175 break;
3178 /* Destination must be full surface or match the clipping rectangle */
3179 if(This->clipper && ((IWineD3DClipperImpl *) This->clipper)->hWnd)
3181 RECT cliprect;
3182 POINT pos[2];
3183 GetClientRect(((IWineD3DClipperImpl *) This->clipper)->hWnd, &cliprect);
3184 pos[0].x = rect.x1;
3185 pos[0].y = rect.y1;
3186 pos[1].x = rect.x2;
3187 pos[1].y = rect.y2;
3188 MapWindowPoints(GetDesktopWindow(), ((IWineD3DClipperImpl *) This->clipper)->hWnd,
3189 pos, 2);
3191 if(pos[0].x != cliprect.left || pos[0].y != cliprect.top ||
3192 pos[1].x != cliprect.right || pos[1].y != cliprect.bottom)
3194 TRACE("No, dest rectangle doesn't match(clipper)\n");
3195 TRACE("Clip rect at (%d,%d)-(%d,%d)\n", cliprect.left, cliprect.top, cliprect.right, cliprect.bottom);
3196 TRACE("Blt dest: (%d,%d)-(%d,%d)\n", rect.x1, rect.y1, rect.x2, rect.y2);
3197 break;
3200 else
3202 if(rect.x1 != 0 || rect.y1 != 0 ||
3203 rect.x2 != This->currentDesc.Width || rect.y2 != This->currentDesc.Height) {
3204 TRACE("No, dest rectangle doesn't match(surface size)\n");
3205 break;
3209 TRACE("Yes\n");
3211 /* These flags are unimportant for the flag check, remove them */
3212 if((Flags & ~(WINEDDBLT_DONOTWAIT | WINEDDBLT_WAIT)) == 0) {
3213 WINED3DSWAPEFFECT orig_swap = dstSwapchain->presentParms.SwapEffect;
3215 /* The idea behind this is that a glReadPixels and a glDrawPixels call
3216 * take very long, while a flip is fast.
3217 * This applies to Half-Life, which does such Blts every time it finished
3218 * a frame, and to Prince of Persia 3D, which uses this to draw at least the main
3219 * menu. This is also used by all apps when they do windowed rendering
3221 * The problem is that flipping is not really the same as copying. After a
3222 * Blt the front buffer is a copy of the back buffer, and the back buffer is
3223 * untouched. Therefore it's necessary to override the swap effect
3224 * and to set it back after the flip.
3226 * Windowed Direct3D < 7 apps do the same. The D3D7 sdk demos are nice
3227 * testcases.
3230 dstSwapchain->presentParms.SwapEffect = WINED3DSWAPEFFECT_COPY;
3231 dstSwapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
3233 TRACE("Full screen back buffer -> front buffer blt, performing a flip instead\n");
3234 IWineD3DSwapChain_Present((IWineD3DSwapChain *) dstSwapchain, NULL, NULL, 0, NULL, 0);
3236 dstSwapchain->presentParms.SwapEffect = orig_swap;
3238 return WINED3D_OK;
3240 break;
3243 TRACE("Unsupported blit between buffers on the same swapchain\n");
3244 return WINED3DERR_INVALIDCALL;
3245 } else if(dstSwapchain && dstSwapchain == srcSwapchain) {
3246 FIXME("Implement hardware blit between two surfaces on the same swapchain\n");
3247 return WINED3DERR_INVALIDCALL;
3248 } else if(dstSwapchain && srcSwapchain) {
3249 FIXME("Implement hardware blit between two different swapchains\n");
3250 return WINED3DERR_INVALIDCALL;
3251 } else if(dstSwapchain) {
3252 if(SrcSurface == myDevice->render_targets[0]) {
3253 TRACE("Blit from active render target to a swapchain\n");
3254 /* Handled with regular texture -> swapchain blit */
3256 } else if(srcSwapchain && This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
3257 FIXME("Implement blit from a swapchain to the active render target\n");
3258 return WINED3DERR_INVALIDCALL;
3261 if((srcSwapchain || SrcSurface == myDevice->render_targets[0]) && !dstSwapchain) {
3262 /* Blit from render target to texture */
3263 WINED3DRECT srect;
3264 BOOL upsideDown, stretchx;
3265 BOOL paletteOverride = FALSE;
3267 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3268 TRACE("Color keying not supported by frame buffer to texture blit\n");
3269 return WINED3DERR_INVALIDCALL;
3270 /* Destination color key is checked above */
3273 /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
3274 * glCopyTexSubImage is a bit picky about the parameters we pass to it
3276 if(SrcRect) {
3277 if(SrcRect->top < SrcRect->bottom) {
3278 srect.y1 = SrcRect->top;
3279 srect.y2 = SrcRect->bottom;
3280 upsideDown = FALSE;
3281 } else {
3282 srect.y1 = SrcRect->bottom;
3283 srect.y2 = SrcRect->top;
3284 upsideDown = TRUE;
3286 srect.x1 = SrcRect->left;
3287 srect.x2 = SrcRect->right;
3288 } else {
3289 srect.x1 = 0;
3290 srect.y1 = 0;
3291 srect.x2 = Src->currentDesc.Width;
3292 srect.y2 = Src->currentDesc.Height;
3293 upsideDown = FALSE;
3295 if(rect.x1 > rect.x2) {
3296 UINT tmp = rect.x2;
3297 rect.x2 = rect.x1;
3298 rect.x1 = tmp;
3299 upsideDown = !upsideDown;
3302 if(rect.x2 - rect.x1 != srect.x2 - srect.x1) {
3303 stretchx = TRUE;
3304 } else {
3305 stretchx = FALSE;
3308 /* When blitting from a render target a texture, the texture isn't required to have a palette.
3309 * In this case grab the palette from the render target. */
3310 if((This->resource.format == WINED3DFMT_P8) && (This->palette == NULL)) {
3311 paletteOverride = TRUE;
3312 TRACE("Source surface (%p) lacks palette, overriding palette with palette %p of destination surface (%p)\n", Src, This->palette, This);
3313 This->palette = Src->palette;
3316 /* Blt is a pretty powerful call, while glCopyTexSubImage2D is not. glCopyTexSubImage cannot
3317 * flip the image nor scale it.
3319 * -> If the app asks for a unscaled, upside down copy, just perform one glCopyTexSubImage2D call
3320 * -> If the app wants a image width an unscaled width, copy it line per line
3321 * -> If the app wants a image that is scaled on the x axis, and the destination rectangle is smaller
3322 * than the frame buffer, draw an upside down scaled image onto the fb, read it back and restore the
3323 * back buffer. This is slower than reading line per line, thus not used for flipping
3324 * -> If the app wants a scaled image with a dest rect that is bigger than the fb, it has to be copied
3325 * pixel by pixel
3327 * If EXT_framebuffer_blit is supported that can be used instead. Note that EXT_framebuffer_blit implies
3328 * FBO support, so it doesn't really make sense to try and make it work with different offscreen rendering
3329 * backends.
3331 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && GL_SUPPORT(EXT_FRAMEBUFFER_BLIT)) {
3332 stretch_rect_fbo((IWineD3DDevice *)myDevice, SrcSurface, &srect,
3333 (IWineD3DSurface *)This, &rect, Filter, upsideDown);
3334 } else if((!stretchx) || rect.x2 - rect.x1 > Src->currentDesc.Width ||
3335 rect.y2 - rect.y1 > Src->currentDesc.Height) {
3336 TRACE("No stretching in x direction, using direct framebuffer -> texture copy\n");
3337 fb_copy_to_texture_direct(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
3338 } else {
3339 TRACE("Using hardware stretching to flip / stretch the texture\n");
3340 fb_copy_to_texture_hwstretch(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
3343 /* Clear the palette as the surface didn't have a palette attached, it would confuse GetPalette and other calls */
3344 if(paletteOverride)
3345 This->palette = NULL;
3347 if(!(This->Flags & SFLAG_DONOTFREE)) {
3348 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
3349 This->resource.allocatedMemory = NULL;
3350 This->resource.heapMemory = NULL;
3351 } else {
3352 This->Flags &= ~SFLAG_INSYSMEM;
3354 /* The texture is now most up to date - If the surface is a render target and has a drawable, this
3355 * path is never entered
3357 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) This, SFLAG_INTEXTURE, TRUE);
3359 return WINED3D_OK;
3360 } else if(Src) {
3361 /* Blit from offscreen surface to render target */
3362 float glTexCoord[4];
3363 DWORD oldCKeyFlags = Src->CKeyFlags;
3364 WINEDDCOLORKEY oldBltCKey = Src->SrcBltCKey;
3365 RECT SourceRectangle;
3366 BOOL paletteOverride = FALSE;
3367 GLenum buffer;
3369 TRACE("Blt from surface %p to rendertarget %p\n", Src, This);
3371 if(SrcRect) {
3372 SourceRectangle.left = SrcRect->left;
3373 SourceRectangle.right = SrcRect->right;
3374 SourceRectangle.top = SrcRect->top;
3375 SourceRectangle.bottom = SrcRect->bottom;
3376 } else {
3377 SourceRectangle.left = 0;
3378 SourceRectangle.right = Src->currentDesc.Width;
3379 SourceRectangle.top = 0;
3380 SourceRectangle.bottom = Src->currentDesc.Height;
3383 /* When blitting from an offscreen surface to a rendertarget, the source
3384 * surface is not required to have a palette. Our rendering / conversion
3385 * code further down the road retrieves the palette from the surface, so
3386 * it must have a palette set. */
3387 if((Src->resource.format == WINED3DFMT_P8) && (Src->palette == NULL)) {
3388 paletteOverride = TRUE;
3389 TRACE("Source surface (%p) lacks palette, overriding palette with palette %p of destination surface (%p)\n", Src, This->palette, This);
3390 Src->palette = This->palette;
3393 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && GL_SUPPORT(EXT_FRAMEBUFFER_BLIT) &&
3394 (Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) == 0) {
3395 TRACE("Using stretch_rect_fbo\n");
3396 /* The source is always a texture, but never the currently active render target, and the texture
3397 * contents are never upside down
3399 stretch_rect_fbo((IWineD3DDevice *)myDevice, SrcSurface, (WINED3DRECT *) &SourceRectangle,
3400 (IWineD3DSurface *)This, &rect, Filter, FALSE);
3402 /* Clear the palette as the surface didn't have a palette attached, it would confuse GetPalette and other calls */
3403 if(paletteOverride)
3404 Src->palette = NULL;
3405 return WINED3D_OK;
3408 if(!CalculateTexRect(Src, &SourceRectangle, glTexCoord)) {
3409 /* Fall back to software */
3410 WARN("(%p) Source texture area (%d,%d)-(%d,%d) is too big\n", Src,
3411 SourceRectangle.left, SourceRectangle.top,
3412 SourceRectangle.right, SourceRectangle.bottom);
3413 return WINED3DERR_INVALIDCALL;
3416 /* Color keying: Check if we have to do a color keyed blt,
3417 * and if not check if a color key is activated.
3419 * Just modify the color keying parameters in the surface and restore them afterwards
3420 * The surface keeps track of the color key last used to load the opengl surface.
3421 * PreLoad will catch the change to the flags and color key and reload if necessary.
3423 if(Flags & WINEDDBLT_KEYSRC) {
3424 /* Use color key from surface */
3425 } else if(Flags & WINEDDBLT_KEYSRCOVERRIDE) {
3426 /* Use color key from DDBltFx */
3427 Src->CKeyFlags |= WINEDDSD_CKSRCBLT;
3428 Src->SrcBltCKey = DDBltFx->ddckSrcColorkey;
3429 } else {
3430 /* Do not use color key */
3431 Src->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
3434 /* Now load the surface */
3435 IWineD3DSurface_PreLoad((IWineD3DSurface *) Src);
3438 /* Activate the destination context, set it up for blitting */
3439 ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
3441 if(!dstSwapchain) {
3442 TRACE("Drawing to offscreen buffer\n");
3443 buffer = myDevice->offscreenBuffer;
3444 } else {
3445 buffer = surface_get_gl_buffer((IWineD3DSurface *)This, (IWineD3DSwapChain *)dstSwapchain);
3447 /* Front buffer coordinates are screen coordinates, while OpenGL coordinates are
3448 * window relative. Also beware of the origin difference(top left vs bottom left).
3449 * Also beware that the front buffer's surface size is screen width x screen height,
3450 * whereas the real gl drawable size is the size of the window.
3452 if(buffer == GL_FRONT) {
3453 RECT windowsize;
3454 POINT offset = {0,0};
3455 UINT h;
3456 ClientToScreen(dstSwapchain->win_handle, &offset);
3457 GetClientRect(dstSwapchain->win_handle, &windowsize);
3458 h = windowsize.bottom - windowsize.top;
3459 rect.x1 -= offset.x; rect.x2 -=offset.x;
3460 rect.y1 -= offset.y; rect.y2 -=offset.y;
3461 rect.y1 += This->currentDesc.Height - h; rect.y2 += This->currentDesc.Height - h;
3463 TRACE("Drawing to %#x buffer\n", buffer);
3466 ENTER_GL();
3467 glDrawBuffer(buffer);
3468 checkGLcall("glDrawBuffer");
3470 myDevice->blitter->set_shader((IWineD3DDevice *) myDevice, Src->resource.format,
3471 Src->glDescription.target, Src->pow2Width, Src->pow2Height);
3473 /* Bind the texture */
3474 glBindTexture(Src->glDescription.target, Src->glDescription.textureName);
3475 checkGLcall("glBindTexture");
3477 /* Filtering for StretchRect */
3478 glTexParameteri(Src->glDescription.target, GL_TEXTURE_MAG_FILTER,
3479 magLookup[Filter - WINED3DTEXF_NONE]);
3480 checkGLcall("glTexParameteri");
3481 glTexParameteri(Src->glDescription.target, GL_TEXTURE_MIN_FILTER,
3482 minMipLookup[Filter][WINED3DTEXF_NONE]);
3483 checkGLcall("glTexParameteri");
3484 glTexParameteri(Src->glDescription.target, GL_TEXTURE_WRAP_S, GL_CLAMP);
3485 glTexParameteri(Src->glDescription.target, GL_TEXTURE_WRAP_T, GL_CLAMP);
3486 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
3487 checkGLcall("glTexEnvi");
3489 /* This is for color keying */
3490 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3491 glEnable(GL_ALPHA_TEST);
3492 checkGLcall("glEnable GL_ALPHA_TEST");
3494 /* When the primary render target uses P8, the alpha component contains the palette index.
3495 * Which means that the colorkey is one of the palette entries. In other cases pixels that
3496 * should be masked away have alpha set to 0. */
3497 if(primary_render_target_is_p8(myDevice))
3498 glAlphaFunc(GL_NOTEQUAL, (float)Src->SrcBltCKey.dwColorSpaceLowValue / 256.0);
3499 else
3500 glAlphaFunc(GL_NOTEQUAL, 0.0);
3501 checkGLcall("glAlphaFunc\n");
3502 } else {
3503 glDisable(GL_ALPHA_TEST);
3504 checkGLcall("glDisable GL_ALPHA_TEST");
3507 /* Draw a textured quad
3509 glBegin(GL_QUADS);
3511 glColor3d(1.0f, 1.0f, 1.0f);
3512 glTexCoord2f(glTexCoord[0], glTexCoord[2]);
3513 glVertex3f(rect.x1,
3514 rect.y1,
3515 0.0);
3517 glTexCoord2f(glTexCoord[0], glTexCoord[3]);
3518 glVertex3f(rect.x1, rect.y2, 0.0);
3520 glTexCoord2f(glTexCoord[1], glTexCoord[3]);
3521 glVertex3f(rect.x2,
3522 rect.y2,
3523 0.0);
3525 glTexCoord2f(glTexCoord[1], glTexCoord[2]);
3526 glVertex3f(rect.x2,
3527 rect.y1,
3528 0.0);
3529 glEnd();
3530 checkGLcall("glEnd");
3532 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3533 glDisable(GL_ALPHA_TEST);
3534 checkGLcall("glDisable(GL_ALPHA_TEST)");
3537 glBindTexture(Src->glDescription.target, 0);
3538 checkGLcall("glBindTexture(Src->glDescription.target, 0)");
3539 /* Leave the opengl state valid for blitting */
3540 myDevice->blitter->unset_shader((IWineD3DDevice *) myDevice);
3542 /* The draw buffer should only need to be restored if we were drawing to the front buffer, and there is a back buffer.
3543 * otherwise the context manager should choose between GL_BACK / offscreenDrawBuffer
3545 if(dstSwapchain && This == (IWineD3DSurfaceImpl *) dstSwapchain->frontBuffer && dstSwapchain->backBuffer) {
3546 glDrawBuffer(GL_BACK);
3547 checkGLcall("glDrawBuffer");
3549 /* Restore the color key parameters */
3550 Src->CKeyFlags = oldCKeyFlags;
3551 Src->SrcBltCKey = oldBltCKey;
3553 /* Clear the palette as the surface didn't have a palette attached, it would confuse GetPalette and other calls */
3554 if(paletteOverride)
3555 Src->palette = NULL;
3557 LEAVE_GL();
3559 /* Flush in case the drawable is used by multiple GL contexts */
3560 if(dstSwapchain && (This == (IWineD3DSurfaceImpl *) dstSwapchain->frontBuffer || dstSwapchain->num_contexts >= 2))
3561 glFlush();
3563 /* TODO: If the surface is locked often, perform the Blt in software on the memory instead */
3564 /* The surface is now in the drawable. On onscreen surfaces or without fbos the texture
3565 * is outdated now
3567 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) This, SFLAG_INDRAWABLE, TRUE);
3568 /* TODO: This should be moved to ModifyLocation() */
3569 if(!(dstSwapchain || wined3d_settings.offscreen_rendering_mode != ORM_FBO)) {
3570 This->Flags |= SFLAG_INTEXTURE;
3573 return WINED3D_OK;
3574 } else {
3575 /* Source-Less Blit to render target */
3576 if (Flags & WINEDDBLT_COLORFILL) {
3577 /* This is easy to handle for the D3D Device... */
3578 DWORD color;
3580 TRACE("Colorfill\n");
3582 /* This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0] || dstSwapchain
3583 must be true if we are here */
3584 if (This != (IWineD3DSurfaceImpl *) myDevice->render_targets[0] &&
3585 !(This == (IWineD3DSurfaceImpl*) dstSwapchain->frontBuffer ||
3586 (dstSwapchain->backBuffer && This == (IWineD3DSurfaceImpl*) dstSwapchain->backBuffer[0]))) {
3587 TRACE("Surface is higher back buffer, falling back to software\n");
3588 return WINED3DERR_INVALIDCALL;
3591 /* The color as given in the Blt function is in the format of the frame-buffer...
3592 * 'clear' expect it in ARGB format => we need to do some conversion :-)
3594 if (This->resource.format == WINED3DFMT_P8) {
3595 DWORD alpha;
3597 if (primary_render_target_is_p8(myDevice)) alpha = DDBltFx->u5.dwFillColor << 24;
3598 else alpha = 0xFF000000;
3600 if (This->palette) {
3601 color = (alpha |
3602 (This->palette->palents[DDBltFx->u5.dwFillColor].peRed << 16) |
3603 (This->palette->palents[DDBltFx->u5.dwFillColor].peGreen << 8) |
3604 (This->palette->palents[DDBltFx->u5.dwFillColor].peBlue));
3605 } else {
3606 color = alpha;
3609 else if (This->resource.format == WINED3DFMT_R5G6B5) {
3610 if (DDBltFx->u5.dwFillColor == 0xFFFF) {
3611 color = 0xFFFFFFFF;
3612 } else {
3613 color = ((0xFF000000) |
3614 ((DDBltFx->u5.dwFillColor & 0xF800) << 8) |
3615 ((DDBltFx->u5.dwFillColor & 0x07E0) << 5) |
3616 ((DDBltFx->u5.dwFillColor & 0x001F) << 3));
3619 else if ((This->resource.format == WINED3DFMT_R8G8B8) ||
3620 (This->resource.format == WINED3DFMT_X8R8G8B8) ) {
3621 color = 0xFF000000 | DDBltFx->u5.dwFillColor;
3623 else if (This->resource.format == WINED3DFMT_A8R8G8B8) {
3624 color = DDBltFx->u5.dwFillColor;
3626 else {
3627 ERR("Wrong surface type for BLT override(Format doesn't match) !\n");
3628 return WINED3DERR_INVALIDCALL;
3631 TRACE("(%p) executing Render Target override, color = %x\n", This, color);
3632 IWineD3DDeviceImpl_ClearSurface(myDevice, This,
3633 1, /* Number of rectangles */
3634 &rect, WINED3DCLEAR_TARGET, color,
3635 0.0 /* Z */,
3636 0 /* Stencil */);
3637 return WINED3D_OK;
3641 /* Default: Fall back to the generic blt. Not an error, a TRACE is enough */
3642 TRACE("Didn't find any usable render target setup for hw blit, falling back to software\n");
3643 return WINED3DERR_INVALIDCALL;
3646 static HRESULT WINAPI IWineD3DSurfaceImpl_BltZ(IWineD3DSurfaceImpl *This, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx)
3648 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3649 float depth;
3651 if (Flags & WINEDDBLT_DEPTHFILL) {
3652 switch(This->resource.format) {
3653 case WINED3DFMT_D16:
3654 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000ffff;
3655 break;
3656 case WINED3DFMT_D15S1:
3657 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000fffe;
3658 break;
3659 case WINED3DFMT_D24S8:
3660 case WINED3DFMT_D24X8:
3661 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00ffffff;
3662 break;
3663 case WINED3DFMT_D32:
3664 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0xffffffff;
3665 break;
3666 default:
3667 depth = 0.0;
3668 ERR("Unexpected format for depth fill: %s\n", debug_d3dformat(This->resource.format));
3671 return IWineD3DDevice_Clear((IWineD3DDevice *) myDevice,
3672 DestRect == NULL ? 0 : 1,
3673 (WINED3DRECT *) DestRect,
3674 WINED3DCLEAR_ZBUFFER,
3675 0x00000000,
3676 depth,
3677 0x00000000);
3680 FIXME("(%p): Unsupp depthstencil blit\n", This);
3681 return WINED3DERR_INVALIDCALL;
3684 static HRESULT WINAPI IWineD3DSurfaceImpl_Blt(IWineD3DSurface *iface, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
3685 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3686 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
3687 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3688 TRACE("(%p)->(%p,%p,%p,%x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3689 TRACE("(%p): Usage is %s\n", This, debug_d3dusage(This->resource.usage));
3691 if ( (This->Flags & SFLAG_LOCKED) || ((Src != NULL) && (Src->Flags & SFLAG_LOCKED)))
3693 WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3694 return WINEDDERR_SURFACEBUSY;
3697 /* Accessing the depth stencil is supposed to fail between a BeginScene and EndScene pair,
3698 * except depth blits, which seem to work
3700 if(iface == myDevice->stencilBufferTarget || (SrcSurface && SrcSurface == myDevice->stencilBufferTarget)) {
3701 if(myDevice->inScene && !(Flags & WINEDDBLT_DEPTHFILL)) {
3702 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3703 return WINED3DERR_INVALIDCALL;
3704 } else if(IWineD3DSurfaceImpl_BltZ(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx) == WINED3D_OK) {
3705 TRACE("Z Blit override handled the blit\n");
3706 return WINED3D_OK;
3710 /* Special cases for RenderTargets */
3711 if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3712 ( Src && (Src->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3713 if(IWineD3DSurfaceImpl_BltOverride(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter) == WINED3D_OK) return WINED3D_OK;
3716 /* For the rest call the X11 surface implementation.
3717 * For RenderTargets this should be implemented OpenGL accelerated in BltOverride,
3718 * other Blts are rather rare
3720 return IWineD3DBaseSurfaceImpl_Blt(iface, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter);
3723 HRESULT WINAPI IWineD3DSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty, IWineD3DSurface *Source, RECT *rsrc, DWORD trans) {
3724 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3725 IWineD3DSurfaceImpl *srcImpl = (IWineD3DSurfaceImpl *) Source;
3726 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3727 TRACE("(%p)->(%d, %d, %p, %p, %08x\n", iface, dstx, dsty, Source, rsrc, trans);
3729 if ( (This->Flags & SFLAG_LOCKED) || ((srcImpl != NULL) && (srcImpl->Flags & SFLAG_LOCKED)))
3731 WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3732 return WINEDDERR_SURFACEBUSY;
3735 if(myDevice->inScene &&
3736 (iface == myDevice->stencilBufferTarget ||
3737 (Source && Source == myDevice->stencilBufferTarget))) {
3738 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3739 return WINED3DERR_INVALIDCALL;
3742 /* Special cases for RenderTargets */
3743 if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3744 ( srcImpl && (srcImpl->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3746 RECT SrcRect, DstRect;
3747 DWORD Flags=0;
3749 if(rsrc) {
3750 SrcRect.left = rsrc->left;
3751 SrcRect.top= rsrc->top;
3752 SrcRect.bottom = rsrc->bottom;
3753 SrcRect.right = rsrc->right;
3754 } else {
3755 SrcRect.left = 0;
3756 SrcRect.top = 0;
3757 SrcRect.right = srcImpl->currentDesc.Width;
3758 SrcRect.bottom = srcImpl->currentDesc.Height;
3761 DstRect.left = dstx;
3762 DstRect.top=dsty;
3763 DstRect.right = dstx + SrcRect.right - SrcRect.left;
3764 DstRect.bottom = dsty + SrcRect.bottom - SrcRect.top;
3766 /* Convert BltFast flags into Btl ones because it is called from SurfaceImpl_Blt as well */
3767 if(trans & WINEDDBLTFAST_SRCCOLORKEY)
3768 Flags |= WINEDDBLT_KEYSRC;
3769 if(trans & WINEDDBLTFAST_DESTCOLORKEY)
3770 Flags |= WINEDDBLT_KEYDEST;
3771 if(trans & WINEDDBLTFAST_WAIT)
3772 Flags |= WINEDDBLT_WAIT;
3773 if(trans & WINEDDBLTFAST_DONOTWAIT)
3774 Flags |= WINEDDBLT_DONOTWAIT;
3776 if(IWineD3DSurfaceImpl_BltOverride(This, &DstRect, Source, &SrcRect, Flags, NULL, WINED3DTEXF_POINT) == WINED3D_OK) return WINED3D_OK;
3780 return IWineD3DBaseSurfaceImpl_BltFast(iface, dstx, dsty, Source, rsrc, trans);
3783 HRESULT WINAPI IWineD3DSurfaceImpl_RealizePalette(IWineD3DSurface *iface) {
3784 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3785 RGBQUAD col[256];
3786 IWineD3DPaletteImpl *pal = This->palette;
3787 unsigned int n;
3788 TRACE("(%p)\n", This);
3790 if (!pal) return WINED3D_OK;
3792 if(This->resource.format == WINED3DFMT_P8 ||
3793 This->resource.format == WINED3DFMT_A8P8)
3795 int bpp;
3796 GLenum format, internal, type;
3797 CONVERT_TYPES convert;
3799 /* Check if we are using a RTL mode which uses texturing for uploads */
3800 BOOL use_texture = (wined3d_settings.rendertargetlock_mode == RTL_READTEX || wined3d_settings.rendertargetlock_mode == RTL_TEXTEX);
3802 /* Check if we have hardware palette conversion if we have convert is set to NO_CONVERSION */
3803 d3dfmt_get_conv(This, TRUE, use_texture, &format, &internal, &type, &convert, &bpp, This->srgb);
3805 if((This->resource.usage & WINED3DUSAGE_RENDERTARGET) && (convert == NO_CONVERSION))
3807 ENTER_GL();
3808 if (This->glDescription.textureName == 0) {
3809 glGenTextures(1, &This->glDescription.textureName);
3810 checkGLcall("glGenTextures");
3812 glBindTexture(This->glDescription.target, This->glDescription.textureName);
3813 checkGLcall("glBindTexture(This->glDescription.target, This->glDescription.textureName)");
3814 LEAVE_GL();
3816 /* Make sure the texture is up to date. This call doesn't do anything if the texture is already up to date. */
3817 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL);
3819 /* We want to force a palette refresh, so mark the drawable as not being up to date */
3820 IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, FALSE);
3822 /* Re-upload the palette */
3823 d3dfmt_p8_upload_palette(iface, convert);
3825 /* Without this some palette updates are missed. This at least happens on Nvidia drivers but
3826 * it works fine using Mesa. */
3827 glFlush();
3828 } else {
3829 if(!(This->Flags & SFLAG_INSYSMEM)) {
3830 TRACE("Palette changed with surface that does not have an up to date system memory copy\n");
3831 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
3833 TRACE("Dirtifying surface\n");
3834 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
3838 if(This->Flags & SFLAG_DIBSECTION) {
3839 TRACE("(%p): Updating the hdc's palette\n", This);
3840 for (n=0; n<256; n++) {
3841 col[n].rgbRed = pal->palents[n].peRed;
3842 col[n].rgbGreen = pal->palents[n].peGreen;
3843 col[n].rgbBlue = pal->palents[n].peBlue;
3844 col[n].rgbReserved = 0;
3846 SetDIBColorTable(This->hDC, 0, 256, col);
3849 /* Propagate the changes to the drawable when we have a palette. */
3850 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3851 IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, NULL);
3853 return WINED3D_OK;
3856 static HRESULT WINAPI IWineD3DSurfaceImpl_PrivateSetup(IWineD3DSurface *iface) {
3857 /** Check against the maximum texture sizes supported by the video card **/
3858 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3859 unsigned int pow2Width, pow2Height;
3860 const GlPixelFormatDesc *glDesc;
3862 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
3863 /* Setup some glformat defaults */
3864 This->glDescription.glFormat = glDesc->glFormat;
3865 This->glDescription.glFormatInternal = glDesc->glInternal;
3866 This->glDescription.glType = glDesc->glType;
3868 This->glDescription.textureName = 0;
3869 This->glDescription.target = GL_TEXTURE_2D;
3871 /* Non-power2 support */
3872 if (GL_SUPPORT(ARB_TEXTURE_NON_POWER_OF_TWO) || GL_SUPPORT(WINE_NORMALIZED_TEXRECT)) {
3873 pow2Width = This->currentDesc.Width;
3874 pow2Height = This->currentDesc.Height;
3875 } else {
3876 /* Find the nearest pow2 match */
3877 pow2Width = pow2Height = 1;
3878 while (pow2Width < This->currentDesc.Width) pow2Width <<= 1;
3879 while (pow2Height < This->currentDesc.Height) pow2Height <<= 1;
3881 This->pow2Width = pow2Width;
3882 This->pow2Height = pow2Height;
3884 if (pow2Width > This->currentDesc.Width || pow2Height > This->currentDesc.Height) {
3885 WINED3DFORMAT Format = This->resource.format;
3886 /** TODO: add support for non power two compressed textures **/
3887 if (Format == WINED3DFMT_DXT1 || Format == WINED3DFMT_DXT2 || Format == WINED3DFMT_DXT3
3888 || Format == WINED3DFMT_DXT4 || Format == WINED3DFMT_DXT5
3889 || This->resource.format == WINED3DFMT_ATI2N) {
3890 FIXME("(%p) Compressed non-power-two textures are not supported w(%d) h(%d)\n",
3891 This, This->currentDesc.Width, This->currentDesc.Height);
3892 return WINED3DERR_NOTAVAILABLE;
3896 if(pow2Width != This->currentDesc.Width ||
3897 pow2Height != This->currentDesc.Height) {
3898 This->Flags |= SFLAG_NONPOW2;
3901 TRACE("%p\n", This);
3902 if ((This->pow2Width > GL_LIMITS(texture_size) || This->pow2Height > GL_LIMITS(texture_size)) && !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL))) {
3903 /* one of three options
3904 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)
3905 2: Set the texture to the maximum size (bad idea)
3906 3: WARN and return WINED3DERR_NOTAVAILABLE;
3907 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.
3909 WARN("(%p) Creating an oversized surface\n", This);
3910 This->Flags |= SFLAG_OVERSIZE;
3912 /* This will be initialized on the first blt */
3913 This->glRect.left = 0;
3914 This->glRect.top = 0;
3915 This->glRect.right = 0;
3916 This->glRect.bottom = 0;
3917 } else {
3918 /* Check this after the oversize check - do not make an oversized surface a texture_rectangle one.
3919 Second also don't use ARB_TEXTURE_RECTANGLE in case the surface format is P8 and EXT_PALETTED_TEXTURE
3920 is used in combination with texture uploads (RTL_READTEX/RTL_TEXTEX). The reason is that EXT_PALETTED_TEXTURE
3921 doesn't work in combination with ARB_TEXTURE_RECTANGLE.
3923 if(This->Flags & SFLAG_NONPOW2 && GL_SUPPORT(ARB_TEXTURE_RECTANGLE) &&
3924 !((This->resource.format == WINED3DFMT_P8) && GL_SUPPORT(EXT_PALETTED_TEXTURE) && (wined3d_settings.rendertargetlock_mode == RTL_READTEX || wined3d_settings.rendertargetlock_mode == RTL_TEXTEX)))
3926 This->glDescription.target = GL_TEXTURE_RECTANGLE_ARB;
3927 This->pow2Width = This->currentDesc.Width;
3928 This->pow2Height = This->currentDesc.Height;
3929 This->Flags &= ~(SFLAG_NONPOW2 | SFLAG_NORMCOORD);
3932 /* No oversize, gl rect is the full texture size */
3933 This->Flags &= ~SFLAG_OVERSIZE;
3934 This->glRect.left = 0;
3935 This->glRect.top = 0;
3936 This->glRect.right = This->pow2Width;
3937 This->glRect.bottom = This->pow2Height;
3940 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
3941 switch(wined3d_settings.offscreen_rendering_mode) {
3942 case ORM_FBO: This->get_drawable_size = get_drawable_size_fbo; break;
3943 case ORM_PBUFFER: This->get_drawable_size = get_drawable_size_pbuffer; break;
3944 case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
3948 This->Flags |= SFLAG_INSYSMEM;
3950 return WINED3D_OK;
3953 void surface_modify_ds_location(IWineD3DSurface *iface, DWORD location) {
3954 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3956 TRACE("(%p) New location %#x\n", This, location);
3958 if (location & ~SFLAG_DS_LOCATIONS) {
3959 FIXME("(%p) Invalid location (%#x) specified\n", This, location);
3962 This->Flags &= ~SFLAG_DS_LOCATIONS;
3963 This->Flags |= location;
3966 void surface_load_ds_location(IWineD3DSurface *iface, DWORD location) {
3967 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3968 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
3970 TRACE("(%p) New location %#x\n", This, location);
3972 /* TODO: Make this work for modes other than FBO */
3973 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return;
3975 if (This->Flags & location) {
3976 TRACE("(%p) Location (%#x) is already up to date\n", This, location);
3977 return;
3980 if (This->current_renderbuffer) {
3981 FIXME("(%p) Not supported with fixed up depth stencil\n", This);
3982 return;
3985 if (location == SFLAG_DS_OFFSCREEN) {
3986 if (This->Flags & SFLAG_DS_ONSCREEN) {
3987 GLint old_binding = 0;
3989 TRACE("(%p) Copying onscreen depth buffer to depth texture\n", This);
3991 ENTER_GL();
3993 if (!device->depth_blt_texture) {
3994 glGenTextures(1, &device->depth_blt_texture);
3997 /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
3998 * directly on the FBO texture. That's because we need to flip. */
3999 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
4000 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
4001 glBindTexture(GL_TEXTURE_2D, device->depth_blt_texture);
4002 glCopyTexImage2D(This->glDescription.target,
4003 This->glDescription.level,
4004 This->glDescription.glFormatInternal,
4007 This->currentDesc.Width,
4008 This->currentDesc.Height,
4010 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4011 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4012 glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
4013 glBindTexture(GL_TEXTURE_2D, old_binding);
4015 /* Setup the destination */
4016 if (!device->depth_blt_rb) {
4017 GL_EXTCALL(glGenRenderbuffersEXT(1, &device->depth_blt_rb));
4018 checkGLcall("glGenRenderbuffersEXT");
4020 if (device->depth_blt_rb_w != This->currentDesc.Width
4021 || device->depth_blt_rb_h != This->currentDesc.Height) {
4022 GL_EXTCALL(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, device->depth_blt_rb));
4023 checkGLcall("glBindRenderbufferEXT");
4024 GL_EXTCALL(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA8, This->currentDesc.Width, This->currentDesc.Height));
4025 checkGLcall("glRenderbufferStorageEXT");
4026 device->depth_blt_rb_w = This->currentDesc.Width;
4027 device->depth_blt_rb_h = This->currentDesc.Height;
4030 bind_fbo((IWineD3DDevice *)device, GL_FRAMEBUFFER_EXT, &device->activeContext->dst_fbo);
4031 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, device->depth_blt_rb));
4032 checkGLcall("glFramebufferRenderbufferEXT");
4033 attach_depth_stencil_fbo(device, GL_FRAMEBUFFER_EXT, iface, FALSE);
4035 /* Do the actual blit */
4036 depth_blt((IWineD3DDevice *)device, device->depth_blt_texture);
4037 checkGLcall("depth_blt");
4039 if (device->render_offscreen) {
4040 bind_fbo((IWineD3DDevice *)device, GL_FRAMEBUFFER_EXT, &device->activeContext->fbo);
4041 } else {
4042 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
4043 checkGLcall("glBindFramebuffer()");
4046 LEAVE_GL();
4047 } else {
4048 FIXME("No up to date depth stencil location\n");
4050 } else if (location == SFLAG_DS_ONSCREEN) {
4051 if (This->Flags & SFLAG_DS_OFFSCREEN) {
4052 TRACE("(%p) Copying depth texture to onscreen depth buffer\n", This);
4054 ENTER_GL();
4056 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
4057 checkGLcall("glBindFramebuffer()");
4058 depth_blt((IWineD3DDevice *)device, This->glDescription.textureName);
4059 checkGLcall("depth_blt");
4061 if (device->render_offscreen) {
4062 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, device->activeContext->fbo));
4063 checkGLcall("glBindFramebuffer()");
4066 LEAVE_GL();
4067 } else {
4068 FIXME("No up to date depth stencil location\n");
4070 } else {
4071 ERR("(%p) Invalid location (%#x) specified\n", This, location);
4074 This->Flags |= location;
4077 static void WINAPI IWineD3DSurfaceImpl_ModifyLocation(IWineD3DSurface *iface, DWORD flag, BOOL persistent) {
4078 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4079 IWineD3DBaseTexture *texture;
4080 IWineD3DSurfaceImpl *overlay;
4082 TRACE("(%p)->(%s, %s)\n", iface,
4083 flag == SFLAG_INSYSMEM ? "SFLAG_INSYSMEM" : flag == SFLAG_INDRAWABLE ? "SFLAG_INDRAWABLE" : "SFLAG_INTEXTURE",
4084 persistent ? "TRUE" : "FALSE");
4086 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
4087 IWineD3DSwapChain *swapchain = NULL;
4089 if (SUCCEEDED(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
4090 TRACE("Surface %p is an onscreen surface\n", iface);
4092 IWineD3DSwapChain_Release(swapchain);
4093 } else {
4094 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4095 if (flag & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE)) flag |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4099 if(persistent) {
4100 if((This->Flags & SFLAG_INTEXTURE) && !(flag & SFLAG_INTEXTURE)) {
4101 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
4102 TRACE("Passing to container\n");
4103 IWineD3DBaseTexture_SetDirty(texture, TRUE);
4104 IWineD3DBaseTexture_Release(texture);
4107 This->Flags &= ~SFLAG_LOCATIONS;
4108 This->Flags |= flag;
4110 /* Redraw emulated overlays, if any */
4111 if(flag & SFLAG_INDRAWABLE && !list_empty(&This->overlays)) {
4112 LIST_FOR_EACH_ENTRY(overlay, &This->overlays, IWineD3DSurfaceImpl, overlay_entry) {
4113 IWineD3DSurface_DrawOverlay((IWineD3DSurface *) overlay);
4116 } else {
4117 if((This->Flags & SFLAG_INTEXTURE) && (flag & SFLAG_INTEXTURE)) {
4118 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
4119 TRACE("Passing to container\n");
4120 IWineD3DBaseTexture_SetDirty(texture, TRUE);
4121 IWineD3DBaseTexture_Release(texture);
4124 This->Flags &= ~flag;
4128 struct coords {
4129 GLfloat x, y, z;
4132 static inline void surface_blt_to_drawable(IWineD3DSurfaceImpl *This, const RECT *rect_in) {
4133 struct coords coords[4];
4134 RECT rect;
4135 IWineD3DSwapChain *swapchain = NULL;
4136 IWineD3DBaseTexture *texture = NULL;
4137 HRESULT hr;
4138 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
4140 if(rect_in) {
4141 rect = *rect_in;
4142 } else {
4143 rect.left = 0;
4144 rect.top = 0;
4145 rect.right = This->currentDesc.Width;
4146 rect.bottom = This->currentDesc.Height;
4149 ActivateContext(device, (IWineD3DSurface*)This, CTXUSAGE_BLIT);
4150 ENTER_GL();
4152 if(This->glDescription.target == GL_TEXTURE_RECTANGLE_ARB) {
4153 glEnable(GL_TEXTURE_RECTANGLE_ARB);
4154 checkGLcall("glEnable(GL_TEXTURE_RECTANGLE_ARB)");
4155 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, This->glDescription.textureName);
4156 checkGLcall("GL_TEXTURE_RECTANGLE_ARB, This->glDescription.textureName)");
4157 glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4158 checkGLcall("glTexParameteri");
4159 glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4160 checkGLcall("glTexParameteri");
4162 coords[0].x = rect.left;
4163 coords[0].z = 0;
4165 coords[1].x = rect.left;
4166 coords[1].z = 0;
4168 coords[2].x = rect.right;
4169 coords[2].z = 0;
4171 coords[3].x = rect.right;
4172 coords[3].z = 0;
4174 coords[0].y = rect.top;
4175 coords[1].y = rect.bottom;
4176 coords[2].y = rect.bottom;
4177 coords[3].y = rect.top;
4178 } else if(This->glDescription.target == GL_TEXTURE_2D) {
4179 glEnable(GL_TEXTURE_2D);
4180 checkGLcall("glEnable(GL_TEXTURE_2D)");
4181 glBindTexture(GL_TEXTURE_2D, This->glDescription.textureName);
4182 checkGLcall("GL_TEXTURE_2D, This->glDescription.textureName)");
4183 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4184 checkGLcall("glTexParameteri");
4185 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4186 checkGLcall("glTexParameteri");
4188 coords[0].x = (float)rect.left / This->pow2Width;
4189 coords[0].z = 0;
4191 coords[1].x = (float)rect.left / This->pow2Width;
4192 coords[1].z = 0;
4194 coords[2].x = (float)rect.right / This->pow2Width;
4195 coords[2].z = 0;
4197 coords[3].x = (float)rect.right / This->pow2Width;
4198 coords[3].z = 0;
4200 coords[0].y = (float)rect.top / This->pow2Height;
4201 coords[1].y = (float)rect.bottom / This->pow2Height;
4202 coords[2].y = (float)rect.bottom / This->pow2Height;
4203 coords[3].y = (float)rect.top / This->pow2Height;
4204 } else {
4205 /* Must be a cube map */
4206 glEnable(GL_TEXTURE_CUBE_MAP_ARB);
4207 checkGLcall("glEnable(GL_TEXTURE_CUBE_MAP_ARB)");
4208 glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, This->glDescription.textureName);
4209 checkGLcall("GL_TEXTURE_CUBE_MAP_ARB, This->glDescription.textureName)");
4210 glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4211 checkGLcall("glTexParameteri");
4212 glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4213 checkGLcall("glTexParameteri");
4215 switch(This->glDescription.target) {
4216 case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
4217 coords[0].x = 1; coords[0].y = -1; coords[0].z = 1;
4218 coords[1].x = 1; coords[1].y = 1; coords[1].z = 1;
4219 coords[2].x = 1; coords[2].y = 1; coords[2].z = -1;
4220 coords[3].x = 1; coords[3].y = -1; coords[3].z = -1;
4221 break;
4223 case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
4224 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
4225 coords[1].x = -1; coords[1].y = 1; coords[1].z = 1;
4226 coords[2].x = -1; coords[2].y = 1; coords[2].z = -1;
4227 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
4228 break;
4230 case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
4231 coords[0].x = -1; coords[0].y = 1; coords[0].z = 1;
4232 coords[1].x = 1; coords[1].y = 1; coords[1].z = 1;
4233 coords[2].x = 1; coords[2].y = 1; coords[2].z = -1;
4234 coords[3].x = -1; coords[3].y = 1; coords[3].z = -1;
4235 break;
4237 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
4238 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
4239 coords[1].x = 1; coords[1].y = -1; coords[1].z = 1;
4240 coords[2].x = 1; coords[2].y = -1; coords[2].z = -1;
4241 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
4242 break;
4244 case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
4245 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
4246 coords[1].x = 1; coords[1].y = -1; coords[1].z = 1;
4247 coords[2].x = 1; coords[2].y = -1; coords[2].z = 1;
4248 coords[3].x = -1; coords[3].y = -1; coords[3].z = 1;
4249 break;
4251 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
4252 coords[0].x = -1; coords[0].y = -1; coords[0].z = -1;
4253 coords[1].x = 1; coords[1].y = -1; coords[1].z = -1;
4254 coords[2].x = 1; coords[2].y = -1; coords[2].z = -1;
4255 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
4256 break;
4258 default:
4259 ERR("Unexpected texture target\n");
4260 LEAVE_GL();
4261 return;
4265 glBegin(GL_QUADS);
4266 glTexCoord3fv(&coords[0].x);
4267 glVertex2i(rect.left, device->render_offscreen ? rect.bottom : rect.top);
4269 glTexCoord3fv(&coords[1].x);
4270 glVertex2i(rect.left, device->render_offscreen ? rect.top : rect.bottom);
4272 glTexCoord3fv(&coords[2].x);
4273 glVertex2i(rect.right, device->render_offscreen ? rect.top : rect.bottom);
4275 glTexCoord3fv(&coords[3].x);
4276 glVertex2i(rect.right, device->render_offscreen ? rect.bottom : rect.top);
4277 glEnd();
4278 checkGLcall("glEnd");
4280 if(This->glDescription.target != GL_TEXTURE_2D) {
4281 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
4282 checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
4283 } else {
4284 glDisable(GL_TEXTURE_2D);
4285 checkGLcall("glDisable(GL_TEXTURE_2D)");
4287 LEAVE_GL();
4289 hr = IWineD3DSurface_GetContainer((IWineD3DSurface*)This, &IID_IWineD3DSwapChain, (void **) &swapchain);
4290 if(hr == WINED3D_OK && swapchain) {
4291 /* Make sure to flush the buffers. This is needed in apps like Red Alert II and Tiberian SUN that use multiple WGL contexts. */
4292 if(((IWineD3DSwapChainImpl*)swapchain)->frontBuffer == (IWineD3DSurface*)This ||
4293 ((IWineD3DSwapChainImpl*)swapchain)->num_contexts >= 2)
4294 glFlush();
4296 IWineD3DSwapChain_Release(swapchain);
4297 } else {
4298 /* We changed the filtering settings on the texture. Inform the container about this to get the filters
4299 * reset properly next draw
4301 hr = IWineD3DSurface_GetContainer((IWineD3DSurface*)This, &IID_IWineD3DBaseTexture, (void **) &texture);
4302 if(hr == WINED3D_OK && texture) {
4303 ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
4304 ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
4305 ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
4306 IWineD3DBaseTexture_Release(texture);
4311 /*****************************************************************************
4312 * IWineD3DSurface::LoadLocation
4314 * Copies the current surface data from wherever it is to the requested
4315 * location. The location is one of the surface flags, SFLAG_INSYSMEM,
4316 * SFLAG_INTEXTURE and SFLAG_INDRAWABLE. When the surface is current in
4317 * multiple locations, the gl texture is preferred over the drawable, which is
4318 * preferred over system memory. The PBO counts as system memory. If rect is
4319 * not NULL, only the specified rectangle is copied (only supported for
4320 * sysmem<->drawable copies at the moment). If rect is NULL, the destination
4321 * location is marked up to date after the copy.
4323 * Parameters:
4324 * flag: Surface location flag to be updated
4325 * rect: rectangle to be copied
4327 * Returns:
4328 * WINED3D_OK on success
4329 * WINED3DERR_DEVICELOST on an internal error
4331 *****************************************************************************/
4332 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadLocation(IWineD3DSurface *iface, DWORD flag, const RECT *rect) {
4333 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4334 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
4335 IWineD3DSwapChain *swapchain = NULL;
4336 GLenum format, internal, type;
4337 CONVERT_TYPES convert;
4338 int bpp;
4339 int width, pitch, outpitch;
4340 BYTE *mem;
4342 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
4343 if (SUCCEEDED(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
4344 TRACE("Surface %p is an onscreen surface\n", iface);
4346 IWineD3DSwapChain_Release(swapchain);
4347 } else {
4348 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets.
4349 * Prefer SFLAG_INTEXTURE. */
4350 if (flag == SFLAG_INDRAWABLE) flag = SFLAG_INTEXTURE;
4354 TRACE("(%p)->(%s, %p)\n", iface,
4355 flag == SFLAG_INSYSMEM ? "SFLAG_INSYSMEM" : flag == SFLAG_INDRAWABLE ? "SFLAG_INDRAWABLE" : "SFLAG_INTEXTURE",
4356 rect);
4357 if(rect) {
4358 TRACE("Rectangle: (%d,%d)-(%d,%d)\n", rect->left, rect->top, rect->right, rect->bottom);
4361 if(This->Flags & flag) {
4362 TRACE("Location already up to date\n");
4363 return WINED3D_OK;
4366 if(!(This->Flags & SFLAG_LOCATIONS)) {
4367 ERR("Surface does not have any up to date location\n");
4368 This->Flags |= SFLAG_LOST;
4369 return WINED3DERR_DEVICELOST;
4372 if(flag == SFLAG_INSYSMEM) {
4373 surface_prepare_system_memory(This);
4375 /* Download the surface to system memory */
4376 if(This->Flags & SFLAG_INTEXTURE) {
4377 if(!device->isInDraw) ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
4378 surface_bind_and_dirtify(This);
4380 surface_download_data(This);
4381 } else {
4382 read_from_framebuffer(This, rect,
4383 This->resource.allocatedMemory,
4384 IWineD3DSurface_GetPitch(iface));
4386 } else if(flag == SFLAG_INDRAWABLE) {
4387 if(This->Flags & SFLAG_INTEXTURE) {
4388 surface_blt_to_drawable(This, rect);
4389 } else {
4390 d3dfmt_get_conv(This, TRUE /* We need color keying */, FALSE /* We won't use textures */, &format, &internal, &type, &convert, &bpp, This->srgb);
4392 /* The width is in 'length' not in bytes */
4393 width = This->currentDesc.Width;
4394 pitch = IWineD3DSurface_GetPitch(iface);
4396 /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4397 * but it isn't set (yet) in all cases it is getting called. */
4398 if((convert != NO_CONVERSION) && (This->Flags & SFLAG_PBO)) {
4399 TRACE("Removing the pbo attached to surface %p\n", This);
4400 surface_remove_pbo(This);
4403 if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
4404 int height = This->currentDesc.Height;
4406 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4407 outpitch = width * bpp;
4408 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4410 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4411 if(!mem) {
4412 ERR("Out of memory %d, %d!\n", outpitch, height);
4413 return WINED3DERR_OUTOFVIDEOMEMORY;
4415 d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
4417 This->Flags |= SFLAG_CONVERTED;
4418 } else {
4419 This->Flags &= ~SFLAG_CONVERTED;
4420 mem = This->resource.allocatedMemory;
4423 flush_to_framebuffer_drawpixels(This, format, type, bpp, mem);
4425 /* Don't delete PBO memory */
4426 if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
4427 HeapFree(GetProcessHeap(), 0, mem);
4429 } else /* if(flag == SFLAG_INTEXTURE) */ {
4430 if (This->Flags & SFLAG_INDRAWABLE) {
4431 read_from_framebuffer_texture(This);
4432 } else { /* Upload from system memory */
4433 d3dfmt_get_conv(This, TRUE /* We need color keying */, TRUE /* We will use textures */, &format, &internal, &type, &convert, &bpp, This->srgb);
4435 if(!device->isInDraw) ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
4436 surface_bind_and_dirtify(This);
4437 ENTER_GL();
4439 /* The only place where LoadTexture() might get called when isInDraw=1
4440 * is ActivateContext where lastActiveRenderTarget is preloaded.
4442 if(iface == device->lastActiveRenderTarget && device->isInDraw)
4443 ERR("Reading back render target but SFLAG_INDRAWABLE not set\n");
4445 /* Otherwise: System memory copy must be most up to date */
4447 if(This->CKeyFlags & WINEDDSD_CKSRCBLT) {
4448 This->Flags |= SFLAG_GLCKEY;
4449 This->glCKey = This->SrcBltCKey;
4451 else This->Flags &= ~SFLAG_GLCKEY;
4453 /* The width is in 'length' not in bytes */
4454 width = This->currentDesc.Width;
4455 pitch = IWineD3DSurface_GetPitch(iface);
4457 /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4458 * but it isn't set (yet) in all cases it is getting called. */
4459 if((convert != NO_CONVERSION) && (This->Flags & SFLAG_PBO)) {
4460 TRACE("Removing the pbo attached to surface %p\n", This);
4461 surface_remove_pbo(This);
4464 if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
4465 int height = This->currentDesc.Height;
4467 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4468 outpitch = width * bpp;
4469 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4471 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4472 if(!mem) {
4473 ERR("Out of memory %d, %d!\n", outpitch, height);
4474 return WINED3DERR_OUTOFVIDEOMEMORY;
4476 d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
4478 This->Flags |= SFLAG_CONVERTED;
4479 } else if( (This->resource.format == WINED3DFMT_P8) && (GL_SUPPORT(EXT_PALETTED_TEXTURE) || GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) ) {
4480 d3dfmt_p8_upload_palette(iface, convert);
4481 This->Flags &= ~SFLAG_CONVERTED;
4482 mem = This->resource.allocatedMemory;
4483 } else {
4484 This->Flags &= ~SFLAG_CONVERTED;
4485 mem = This->resource.allocatedMemory;
4488 /* Make sure the correct pitch is used */
4489 glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
4491 if ((This->Flags & SFLAG_NONPOW2) && !(This->Flags & SFLAG_OVERSIZE)) {
4492 TRACE("non power of two support\n");
4493 if(!(This->Flags & SFLAG_ALLOCATED)) {
4494 surface_allocate_surface(This, internal, This->pow2Width, This->pow2Height, format, type);
4496 if (mem || (This->Flags & SFLAG_PBO)) {
4497 surface_upload_data(This, internal, This->currentDesc.Width, This->currentDesc.Height, format, type, mem);
4499 } else {
4500 /* When making the realloc conditional, keep in mind that GL_APPLE_client_storage may be in use, and This->resource.allocatedMemory
4501 * changed. So also keep track of memory changes. In this case the texture has to be reallocated
4503 if(!(This->Flags & SFLAG_ALLOCATED)) {
4504 surface_allocate_surface(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type);
4506 if (mem || (This->Flags & SFLAG_PBO)) {
4507 surface_upload_data(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type, mem);
4511 /* Restore the default pitch */
4512 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
4513 LEAVE_GL();
4515 /* Don't delete PBO memory */
4516 if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
4517 HeapFree(GetProcessHeap(), 0, mem);
4521 if(rect == NULL) {
4522 This->Flags |= flag;
4525 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && !swapchain
4526 && (This->Flags & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE))) {
4527 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4528 This->Flags |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4531 return WINED3D_OK;
4534 HRESULT WINAPI IWineD3DSurfaceImpl_SetContainer(IWineD3DSurface *iface, IWineD3DBase *container) {
4535 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4536 IWineD3DSwapChain *swapchain = NULL;
4538 /* Update the drawable size method */
4539 if(container) {
4540 IWineD3DBase_QueryInterface(container, &IID_IWineD3DSwapChain, (void **) &swapchain);
4542 if(swapchain) {
4543 This->get_drawable_size = get_drawable_size_swapchain;
4544 IWineD3DSwapChain_Release(swapchain);
4545 } else if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
4546 switch(wined3d_settings.offscreen_rendering_mode) {
4547 case ORM_FBO: This->get_drawable_size = get_drawable_size_fbo; break;
4548 case ORM_PBUFFER: This->get_drawable_size = get_drawable_size_pbuffer; break;
4549 case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
4553 return IWineD3DBaseSurfaceImpl_SetContainer(iface, container);
4556 static WINED3DSURFTYPE WINAPI IWineD3DSurfaceImpl_GetImplType(IWineD3DSurface *iface) {
4557 return SURFACE_OPENGL;
4560 static HRESULT WINAPI IWineD3DSurfaceImpl_DrawOverlay(IWineD3DSurface *iface) {
4561 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4562 HRESULT hr;
4564 /* If there's no destination surface there is nothing to do */
4565 if(!This->overlay_dest) return WINED3D_OK;
4567 /* Blt calls ModifyLocation on the dest surface, which in turn calls DrawOverlay to
4568 * update the overlay. Prevent an endless recursion
4570 if(This->overlay_dest->Flags & SFLAG_INOVERLAYDRAW) {
4571 return WINED3D_OK;
4573 This->overlay_dest->Flags |= SFLAG_INOVERLAYDRAW;
4574 hr = IWineD3DSurfaceImpl_Blt((IWineD3DSurface *) This->overlay_dest, &This->overlay_destrect,
4575 iface, &This->overlay_srcrect, WINEDDBLT_WAIT,
4576 NULL, WINED3DTEXF_LINEAR);
4577 This->overlay_dest->Flags &= ~SFLAG_INOVERLAYDRAW;
4579 return hr;
4582 const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl =
4584 /* IUnknown */
4585 IWineD3DBaseSurfaceImpl_QueryInterface,
4586 IWineD3DBaseSurfaceImpl_AddRef,
4587 IWineD3DSurfaceImpl_Release,
4588 /* IWineD3DResource */
4589 IWineD3DBaseSurfaceImpl_GetParent,
4590 IWineD3DBaseSurfaceImpl_GetDevice,
4591 IWineD3DBaseSurfaceImpl_SetPrivateData,
4592 IWineD3DBaseSurfaceImpl_GetPrivateData,
4593 IWineD3DBaseSurfaceImpl_FreePrivateData,
4594 IWineD3DBaseSurfaceImpl_SetPriority,
4595 IWineD3DBaseSurfaceImpl_GetPriority,
4596 IWineD3DSurfaceImpl_PreLoad,
4597 IWineD3DSurfaceImpl_UnLoad,
4598 IWineD3DBaseSurfaceImpl_GetType,
4599 /* IWineD3DSurface */
4600 IWineD3DBaseSurfaceImpl_GetContainer,
4601 IWineD3DBaseSurfaceImpl_GetDesc,
4602 IWineD3DSurfaceImpl_LockRect,
4603 IWineD3DSurfaceImpl_UnlockRect,
4604 IWineD3DSurfaceImpl_GetDC,
4605 IWineD3DSurfaceImpl_ReleaseDC,
4606 IWineD3DSurfaceImpl_Flip,
4607 IWineD3DSurfaceImpl_Blt,
4608 IWineD3DBaseSurfaceImpl_GetBltStatus,
4609 IWineD3DBaseSurfaceImpl_GetFlipStatus,
4610 IWineD3DBaseSurfaceImpl_IsLost,
4611 IWineD3DBaseSurfaceImpl_Restore,
4612 IWineD3DSurfaceImpl_BltFast,
4613 IWineD3DBaseSurfaceImpl_GetPalette,
4614 IWineD3DBaseSurfaceImpl_SetPalette,
4615 IWineD3DSurfaceImpl_RealizePalette,
4616 IWineD3DBaseSurfaceImpl_SetColorKey,
4617 IWineD3DBaseSurfaceImpl_GetPitch,
4618 IWineD3DSurfaceImpl_SetMem,
4619 IWineD3DBaseSurfaceImpl_SetOverlayPosition,
4620 IWineD3DBaseSurfaceImpl_GetOverlayPosition,
4621 IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder,
4622 IWineD3DBaseSurfaceImpl_UpdateOverlay,
4623 IWineD3DBaseSurfaceImpl_SetClipper,
4624 IWineD3DBaseSurfaceImpl_GetClipper,
4625 /* Internal use: */
4626 IWineD3DSurfaceImpl_AddDirtyRect,
4627 IWineD3DSurfaceImpl_LoadTexture,
4628 IWineD3DSurfaceImpl_BindTexture,
4629 IWineD3DSurfaceImpl_SaveSnapshot,
4630 IWineD3DSurfaceImpl_SetContainer,
4631 IWineD3DSurfaceImpl_SetGlTextureDesc,
4632 IWineD3DSurfaceImpl_GetGlDesc,
4633 IWineD3DSurfaceImpl_GetData,
4634 IWineD3DSurfaceImpl_SetFormat,
4635 IWineD3DSurfaceImpl_PrivateSetup,
4636 IWineD3DSurfaceImpl_ModifyLocation,
4637 IWineD3DSurfaceImpl_LoadLocation,
4638 IWineD3DSurfaceImpl_GetImplType,
4639 IWineD3DSurfaceImpl_DrawOverlay
4641 #undef GLINFO_LOCATION
4643 #define GLINFO_LOCATION device->adapter->gl_info
4644 static HRESULT ffp_blit_alloc(IWineD3DDevice *iface) { return WINED3D_OK; }
4645 static void ffp_blit_free(IWineD3DDevice *iface) { }
4647 static HRESULT ffp_blit_set(IWineD3DDevice *iface, WINED3DFORMAT fmt, GLenum textype, UINT width, UINT height) {
4648 glEnable(textype);
4649 checkGLcall("glEnable(textype)");
4650 return WINED3D_OK;
4653 static void ffp_blit_unset(IWineD3DDevice *iface) {
4654 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
4655 glDisable(GL_TEXTURE_2D);
4656 checkGLcall("glDisable(GL_TEXTURE_2D)");
4657 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
4658 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
4659 checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
4661 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
4662 glDisable(GL_TEXTURE_RECTANGLE_ARB);
4663 checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
4667 static BOOL ffp_blit_conv_supported(WINED3DFORMAT fmt) {
4668 TRACE("Checking blit format support for format %s: [FAILED]\n", debug_d3dformat(fmt));
4669 return FALSE;
4672 const struct blit_shader ffp_blit = {
4673 ffp_blit_alloc,
4674 ffp_blit_free,
4675 ffp_blit_set,
4676 ffp_blit_unset,
4677 ffp_blit_conv_supported