push e5b2529cdc55a2e67d855677d8651b2d2fa8d45f
[wine/hacks.git] / dlls / wined3d / surface.c
bloba988121d6ad1bb0ae76bca42514244c0b8c0a151
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 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
960 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
961 ENTER_GL();
963 GL_EXTCALL(glGenBuffersARB(1, &This->pbo));
964 error = glGetError();
965 if(This->pbo == 0 || error != GL_NO_ERROR) {
966 ERR("Failed to bind the PBO with error %s (%#x)\n", debug_glerror(error), error);
969 TRACE("Attaching pbo=%#x to (%p)\n", This->pbo, This);
971 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
972 checkGLcall("glBindBufferARB");
974 GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->resource.size + 4, This->resource.allocatedMemory, GL_STREAM_DRAW_ARB));
975 checkGLcall("glBufferDataARB");
977 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
978 checkGLcall("glBindBufferARB");
980 /* We don't need the system memory anymore and we can't even use it for PBOs */
981 if(!(This->Flags & SFLAG_CLIENT)) {
982 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
983 This->resource.heapMemory = NULL;
985 This->resource.allocatedMemory = NULL;
986 This->Flags |= SFLAG_PBO;
987 LEAVE_GL();
988 } else if(!(This->resource.allocatedMemory || This->Flags & SFLAG_PBO)) {
989 /* Whatever surface we have, make sure that there is memory allocated for the downloaded copy,
990 * or a pbo to map
992 if(!This->resource.heapMemory) {
993 This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
995 This->resource.allocatedMemory =
996 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
997 if(This->Flags & SFLAG_INSYSMEM) {
998 ERR("Surface without memory or pbo has SFLAG_INSYSMEM set!\n");
1003 static HRESULT WINAPI IWineD3DSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags) {
1004 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1005 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
1006 IWineD3DSwapChain *swapchain = NULL;
1008 TRACE("(%p) : rect@%p flags(%08x), output lockedRect@%p, memory@%p\n", This, pRect, Flags, pLockedRect, This->resource.allocatedMemory);
1010 /* This is also done in the base class, but we have to verify this before loading any data from
1011 * gl into the sysmem copy. The PBO may be mapped, a different rectangle locked, the discard flag
1012 * may interfere, and all other bad things may happen
1014 if (This->Flags & SFLAG_LOCKED) {
1015 WARN("Surface is already locked, returning D3DERR_INVALIDCALL\n");
1016 return WINED3DERR_INVALIDCALL;
1018 This->Flags |= SFLAG_LOCKED;
1020 if (!(This->Flags & SFLAG_LOCKABLE))
1022 TRACE("Warning: trying to lock unlockable surf@%p\n", This);
1025 if (Flags & WINED3DLOCK_DISCARD) {
1026 /* Set SFLAG_INSYSMEM, so we'll never try to download the data from the texture. */
1027 TRACE("WINED3DLOCK_DISCARD flag passed, marking local copy as up to date\n");
1028 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1029 This->Flags |= SFLAG_INSYSMEM;
1030 goto lock_end;
1033 if (This->Flags & SFLAG_INSYSMEM) {
1034 TRACE("Local copy is up to date, not downloading data\n");
1035 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1036 goto lock_end;
1039 /* Now download the surface content from opengl
1040 * Use the render target readback if the surface is on a swapchain(=onscreen render target) or the current primary target
1041 * Offscreen targets which are not active at the moment or are higher targets(FBOs) can be locked with the texture path
1043 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain);
1044 if(swapchain || iface == myDevice->render_targets[0]) {
1045 const RECT *pass_rect = pRect;
1047 /* IWineD3DSurface_LoadLocation does not check if the rectangle specifies the full surfaces
1048 * because most caller functions do not need that. So do that here
1050 if(pRect &&
1051 pRect->top == 0 &&
1052 pRect->left == 0 &&
1053 pRect->right == This->currentDesc.Width &&
1054 pRect->bottom == This->currentDesc.Height) {
1055 pass_rect = NULL;
1058 switch(wined3d_settings.rendertargetlock_mode) {
1059 case RTL_TEXDRAW:
1060 case RTL_TEXTEX:
1061 FIXME("Reading from render target with a texture isn't implemented yet, falling back to framebuffer reading\n");
1062 #if 0
1063 /* Disabled for now. LoadLocation prefers the texture over the drawable as the source. So if we copy to the
1064 * texture first, then to sysmem, we'll avoid glReadPixels and use glCopyTexImage and glGetTexImage2D instead.
1065 * This may be faster on some cards
1067 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* No partial texture copy yet */);
1068 #endif
1069 /* drop through */
1071 case RTL_AUTO:
1072 case RTL_READDRAW:
1073 case RTL_READTEX:
1074 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, pRect);
1075 break;
1077 case RTL_DISABLE:
1078 break;
1080 if(swapchain) IWineD3DSwapChain_Release(swapchain);
1082 } else if(iface == myDevice->stencilBufferTarget) {
1083 /** the depth stencil in openGL has a format of GL_FLOAT
1084 * which should be good for WINED3DFMT_D16_LOCKABLE
1085 * and WINED3DFMT_D16
1086 * it is unclear what format the stencil buffer is in except.
1087 * 'Each index is converted to fixed point...
1088 * If GL_MAP_STENCIL is GL_TRUE, indices are replaced by their
1089 * mappings in the table GL_PIXEL_MAP_S_TO_S.
1090 * glReadPixels(This->lockedRect.left,
1091 * This->lockedRect.bottom - j - 1,
1092 * This->lockedRect.right - This->lockedRect.left,
1093 * 1,
1094 * GL_DEPTH_COMPONENT,
1095 * type,
1096 * (char *)pLockedRect->pBits + (pLockedRect->Pitch * (j-This->lockedRect.top)));
1098 * Depth Stencil surfaces which are not the current depth stencil target should have their data in a
1099 * gl texture(next path), or in local memory(early return because of set SFLAG_INSYSMEM above). If
1100 * none of that is the case the problem is not in this function :-)
1101 ********************************************/
1102 FIXME("Depth stencil locking not supported yet\n");
1103 } else {
1104 /* This path is for normal surfaces, offscreen render targets and everything else that is in a gl texture */
1105 TRACE("locking an ordinary surface\n");
1106 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL /* no partial locking for textures yet */);
1109 lock_end:
1110 if(This->Flags & SFLAG_PBO) {
1111 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
1112 ENTER_GL();
1113 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1114 checkGLcall("glBindBufferARB");
1116 /* This shouldn't happen but could occur if some other function didn't handle the PBO properly */
1117 if(This->resource.allocatedMemory) {
1118 ERR("The surface already has PBO memory allocated!\n");
1121 This->resource.allocatedMemory = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1122 checkGLcall("glMapBufferARB");
1124 /* Make sure the pbo isn't set anymore in order not to break non-pbo calls */
1125 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1126 checkGLcall("glBindBufferARB");
1128 LEAVE_GL();
1131 if (Flags & (WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY)) {
1132 /* Don't dirtify */
1133 } else {
1134 IWineD3DBaseTexture *pBaseTexture;
1136 * Dirtify on lock
1137 * as seen in msdn docs
1139 IWineD3DSurface_AddDirtyRect(iface, pRect);
1141 /** Dirtify Container if needed */
1142 if (WINED3D_OK == IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&pBaseTexture) && pBaseTexture != NULL) {
1143 TRACE("Making container dirty\n");
1144 IWineD3DBaseTexture_SetDirty(pBaseTexture, TRUE);
1145 IWineD3DBaseTexture_Release(pBaseTexture);
1146 } else {
1147 TRACE("Surface is standalone, no need to dirty the container\n");
1151 return IWineD3DBaseSurfaceImpl_LockRect(iface, pLockedRect, pRect, Flags);
1154 static void flush_to_framebuffer_drawpixels(IWineD3DSurfaceImpl *This, GLenum fmt, GLenum type, UINT bpp, const BYTE *mem) {
1155 GLint prev_store;
1156 GLint prev_rasterpos[4];
1157 GLint skipBytes = 0;
1158 UINT pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This); /* target is argb, 4 byte */
1159 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
1160 IWineD3DSwapChainImpl *swapchain;
1162 /* Activate the correct context for the render target */
1163 ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
1164 ENTER_GL();
1166 IWineD3DSurface_GetContainer((IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&swapchain);
1167 if(!swapchain) {
1168 /* Primary offscreen render target */
1169 TRACE("Offscreen render target\n");
1170 glDrawBuffer(myDevice->offscreenBuffer);
1171 checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
1172 } else {
1173 GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *) This, (IWineD3DSwapChain *)swapchain);
1174 TRACE("Unlocking %#x buffer\n", buffer);
1175 glDrawBuffer(buffer);
1176 checkGLcall("glDrawBuffer");
1178 IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapchain);
1181 glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
1182 vcheckGLcall("glIntegerv");
1183 glGetIntegerv(GL_CURRENT_RASTER_POSITION, &prev_rasterpos[0]);
1184 vcheckGLcall("glIntegerv");
1185 glPixelZoom(1.0, -1.0);
1186 vcheckGLcall("glPixelZoom");
1188 /* If not fullscreen, we need to skip a number of bytes to find the next row of data */
1189 glGetIntegerv(GL_UNPACK_ROW_LENGTH, &skipBytes);
1190 glPixelStorei(GL_UNPACK_ROW_LENGTH, This->currentDesc.Width);
1192 glRasterPos3i(This->lockedRect.left, This->lockedRect.top, 1);
1193 vcheckGLcall("glRasterPos2f");
1195 /* Some drivers(radeon dri, others?) don't like exceptions during
1196 * glDrawPixels. If the surface is a DIB section, it might be in GDIMode
1197 * after ReleaseDC. Reading it will cause an exception, which x11drv will
1198 * catch to put the dib section in InSync mode, which leads to a crash
1199 * and a blocked x server on my radeon card.
1201 * The following lines read the dib section so it is put in InSync mode
1202 * before glDrawPixels is called and the crash is prevented. There won't
1203 * be any interfering gdi accesses, because UnlockRect is called from
1204 * ReleaseDC, and the app won't use the dc any more afterwards.
1206 if((This->Flags & SFLAG_DIBSECTION) && !(This->Flags & SFLAG_PBO)) {
1207 volatile BYTE read;
1208 read = This->resource.allocatedMemory[0];
1211 if(This->Flags & SFLAG_PBO) {
1212 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1213 checkGLcall("glBindBufferARB");
1216 /* When the surface is locked we only have to refresh the locked part else we need to update the whole image */
1217 if(This->Flags & SFLAG_LOCKED) {
1218 glDrawPixels(This->lockedRect.right - This->lockedRect.left,
1219 (This->lockedRect.bottom - This->lockedRect.top)-1,
1220 fmt, type,
1221 mem + bpp * This->lockedRect.left + pitch * This->lockedRect.top);
1222 checkGLcall("glDrawPixels");
1223 } else {
1224 glDrawPixels(This->currentDesc.Width,
1225 This->currentDesc.Height,
1226 fmt, type, mem);
1227 checkGLcall("glDrawPixels");
1230 if(This->Flags & SFLAG_PBO) {
1231 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1232 checkGLcall("glBindBufferARB");
1235 glPixelZoom(1.0,1.0);
1236 vcheckGLcall("glPixelZoom");
1238 glRasterPos3iv(&prev_rasterpos[0]);
1239 vcheckGLcall("glRasterPos3iv");
1241 /* Reset to previous pack row length */
1242 glPixelStorei(GL_UNPACK_ROW_LENGTH, skipBytes);
1243 vcheckGLcall("glPixelStorei GL_UNPACK_ROW_LENGTH");
1245 if(!swapchain) {
1246 glDrawBuffer(myDevice->offscreenBuffer);
1247 checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
1248 } else if(swapchain->backBuffer) {
1249 glDrawBuffer(GL_BACK);
1250 checkGLcall("glDrawBuffer(GL_BACK)");
1251 } else {
1252 glDrawBuffer(GL_FRONT);
1253 checkGLcall("glDrawBuffer(GL_FRONT)");
1255 LEAVE_GL();
1257 return;
1260 static HRESULT WINAPI IWineD3DSurfaceImpl_UnlockRect(IWineD3DSurface *iface) {
1261 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1262 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
1263 IWineD3DSwapChainImpl *swapchain = NULL;
1264 BOOL fullsurface;
1266 if (!(This->Flags & SFLAG_LOCKED)) {
1267 WARN("trying to Unlock an unlocked surf@%p\n", This);
1268 return WINED3DERR_INVALIDCALL;
1271 if (This->Flags & SFLAG_PBO) {
1272 TRACE("Freeing PBO memory\n");
1273 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
1274 ENTER_GL();
1275 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1276 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1277 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1278 checkGLcall("glUnmapBufferARB");
1279 LEAVE_GL();
1280 This->resource.allocatedMemory = NULL;
1283 TRACE("(%p) : dirtyfied(%d)\n", This, This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
1285 if (This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE)) {
1286 TRACE("(%p) : Not Dirtified so nothing to do, return now\n", This);
1287 goto unlock_end;
1290 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain);
1291 if(swapchain || (myDevice->render_targets && iface == myDevice->render_targets[0])) {
1292 if(swapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
1294 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1295 static BOOL warned = FALSE;
1296 if(!warned) {
1297 ERR("The application tries to write to the render target, but render target locking is disabled\n");
1298 warned = TRUE;
1300 goto unlock_end;
1303 if(This->dirtyRect.left == 0 &&
1304 This->dirtyRect.top == 0 &&
1305 This->dirtyRect.right == This->currentDesc.Width &&
1306 This->dirtyRect.bottom == This->currentDesc.Height) {
1307 fullsurface = TRUE;
1308 } else {
1309 /* TODO: Proper partial rectangle tracking */
1310 fullsurface = FALSE;
1311 This->Flags |= SFLAG_INSYSMEM;
1314 switch(wined3d_settings.rendertargetlock_mode) {
1315 case RTL_READTEX:
1316 case RTL_TEXTEX:
1317 ActivateContext(myDevice, iface, CTXUSAGE_BLIT);
1318 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* partial texture loading not supported yet */);
1319 /* drop through */
1321 case RTL_AUTO:
1322 case RTL_READDRAW:
1323 case RTL_TEXDRAW:
1324 IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, fullsurface ? NULL : &This->dirtyRect);
1325 break;
1328 if(!fullsurface) {
1329 /* Partial rectangle tracking is not commonly implemented, it is only done for render targets. Overwrite
1330 * the flags to bring them back into a sane state. INSYSMEM was set before to tell LoadLocation where
1331 * to read the rectangle from. Indrawable is set because all modifications from the partial sysmem copy
1332 * are written back to the drawable, thus the surface is merged again in the drawable. The sysmem copy is
1333 * not fully up to date because only a subrectangle was read in LockRect.
1335 This->Flags &= ~SFLAG_INSYSMEM;
1336 This->Flags |= SFLAG_INDRAWABLE;
1339 This->dirtyRect.left = This->currentDesc.Width;
1340 This->dirtyRect.top = This->currentDesc.Height;
1341 This->dirtyRect.right = 0;
1342 This->dirtyRect.bottom = 0;
1343 } else if(iface == myDevice->stencilBufferTarget) {
1344 FIXME("Depth Stencil buffer locking is not implemented\n");
1345 } else {
1346 /* The rest should be a normal texture */
1347 IWineD3DBaseTextureImpl *impl;
1348 /* Check if the texture is bound, if yes dirtify the sampler to force a re-upload of the texture
1349 * Can't load the texture here because PreLoad may destroy and recreate the gl texture, so sampler
1350 * states need resetting
1352 if(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&impl) == WINED3D_OK) {
1353 if(impl->baseTexture.bindCount) {
1354 IWineD3DDeviceImpl_MarkStateDirty(myDevice, STATE_SAMPLER(impl->baseTexture.sampler));
1356 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *) impl);
1360 unlock_end:
1361 This->Flags &= ~SFLAG_LOCKED;
1362 memset(&This->lockedRect, 0, sizeof(RECT));
1364 /* Overlays have to be redrawn manually after changes with the GL implementation */
1365 if(This->overlay_dest) {
1366 IWineD3DSurface_DrawOverlay(iface);
1368 return WINED3D_OK;
1371 HRESULT WINAPI IWineD3DSurfaceImpl_GetDC(IWineD3DSurface *iface, HDC *pHDC) {
1372 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1373 WINED3DLOCKED_RECT lock;
1374 HRESULT hr;
1375 RGBQUAD col[256];
1377 TRACE("(%p)->(%p)\n",This,pHDC);
1379 if(This->Flags & SFLAG_USERPTR) {
1380 ERR("Not supported on surfaces with an application-provided surfaces\n");
1381 return WINEDDERR_NODC;
1384 /* Give more detailed info for ddraw */
1385 if (This->Flags & SFLAG_DCINUSE)
1386 return WINEDDERR_DCALREADYCREATED;
1388 /* Can't GetDC if the surface is locked */
1389 if (This->Flags & SFLAG_LOCKED)
1390 return WINED3DERR_INVALIDCALL;
1392 /* According to Direct3D9 docs, only these formats are supported */
1393 if (((IWineD3DImpl *)This->resource.wineD3DDevice->wineD3D)->dxVersion > 7) {
1394 if (This->resource.format != WINED3DFMT_R5G6B5 &&
1395 This->resource.format != WINED3DFMT_X1R5G5B5 &&
1396 This->resource.format != WINED3DFMT_R8G8B8 &&
1397 This->resource.format != WINED3DFMT_X8R8G8B8) return WINED3DERR_INVALIDCALL;
1400 memset(&lock, 0, sizeof(lock)); /* To be sure */
1402 /* Create a DIB section if there isn't a hdc yet */
1403 if(!This->hDC) {
1404 IWineD3DBaseSurfaceImpl_CreateDIBSection(iface);
1405 if(This->Flags & SFLAG_CLIENT) {
1406 IWineD3DSurface_PreLoad(iface);
1409 /* Use the dib section from now on if we are not using a PBO */
1410 if(!(This->Flags & SFLAG_PBO))
1411 This->resource.allocatedMemory = This->dib.bitmap_data;
1414 /* Lock the surface */
1415 hr = IWineD3DSurface_LockRect(iface,
1416 &lock,
1417 NULL,
1420 if(This->Flags & SFLAG_PBO) {
1421 /* Sync the DIB with the PBO. This can't be done earlier because LockRect activates the allocatedMemory */
1422 memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, This->dib.bitmap_size);
1425 if(FAILED(hr)) {
1426 ERR("IWineD3DSurface_LockRect failed with hr = %08x\n", hr);
1427 /* keep the dib section */
1428 return hr;
1431 if(This->resource.format == WINED3DFMT_P8 ||
1432 This->resource.format == WINED3DFMT_A8P8) {
1433 /* GetDC on palettized formats is unsupported in D3D9, and the method is missing in
1434 D3D8, so this should only be used for DX <=7 surfaces (with non-device palettes) */
1435 unsigned int n;
1436 PALETTEENTRY *pal = NULL;
1438 if(This->palette) {
1439 pal = This->palette->palents;
1440 } else {
1441 IWineD3DSurfaceImpl *dds_primary;
1442 IWineD3DSwapChainImpl *swapchain;
1443 swapchain = (IWineD3DSwapChainImpl *)This->resource.wineD3DDevice->swapchains[0];
1444 dds_primary = (IWineD3DSurfaceImpl *)swapchain->frontBuffer;
1445 if (dds_primary && dds_primary->palette)
1446 pal = dds_primary->palette->palents;
1449 if (pal) {
1450 for (n=0; n<256; n++) {
1451 col[n].rgbRed = pal[n].peRed;
1452 col[n].rgbGreen = pal[n].peGreen;
1453 col[n].rgbBlue = pal[n].peBlue;
1454 col[n].rgbReserved = 0;
1456 SetDIBColorTable(This->hDC, 0, 256, col);
1460 *pHDC = This->hDC;
1461 TRACE("returning %p\n",*pHDC);
1462 This->Flags |= SFLAG_DCINUSE;
1464 return WINED3D_OK;
1467 HRESULT WINAPI IWineD3DSurfaceImpl_ReleaseDC(IWineD3DSurface *iface, HDC hDC) {
1468 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1470 TRACE("(%p)->(%p)\n",This,hDC);
1472 if (!(This->Flags & SFLAG_DCINUSE))
1473 return WINED3DERR_INVALIDCALL;
1475 if (This->hDC !=hDC) {
1476 WARN("Application tries to release an invalid DC(%p), surface dc is %p\n", hDC, This->hDC);
1477 return WINED3DERR_INVALIDCALL;
1480 if((This->Flags & SFLAG_PBO) && This->resource.allocatedMemory) {
1481 /* Copy the contents of the DIB over to the PBO */
1482 memcpy(This->resource.allocatedMemory, This->dib.bitmap_data, This->dib.bitmap_size);
1485 /* we locked first, so unlock now */
1486 IWineD3DSurface_UnlockRect(iface);
1488 This->Flags &= ~SFLAG_DCINUSE;
1490 return WINED3D_OK;
1493 /* ******************************************************
1494 IWineD3DSurface Internal (No mapping to directx api) parts follow
1495 ****************************************************** */
1497 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) {
1498 BOOL colorkey_active = need_alpha_ck && (This->CKeyFlags & WINEDDSD_CKSRCBLT);
1499 const GlPixelFormatDesc *glDesc;
1500 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1501 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
1503 /* Default values: From the surface */
1504 *format = glDesc->glFormat;
1505 *type = glDesc->glType;
1506 *convert = NO_CONVERSION;
1507 *target_bpp = This->bytesPerPixel;
1509 if(srgb_mode) {
1510 *internal = glDesc->glGammaInternal;
1511 } else if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
1512 *internal = glDesc->rtInternal;
1513 } else {
1514 *internal = glDesc->glInternal;
1517 /* Ok, now look if we have to do any conversion */
1518 switch(This->resource.format) {
1519 case WINED3DFMT_P8:
1520 /* ****************
1521 Paletted Texture
1522 **************** */
1524 /* Use conversion when the paletted texture extension OR fragment shaders are available. When either
1525 * of the two is available make sure texturing is requested as neither of the two works in
1526 * conjunction with calls like glDraw-/glReadPixels. Further also use conversion in case of color keying.
1527 * Paletted textures can be emulated using shaders but only do that for 2D purposes e.g. situations
1528 * in which the main render target uses p8. Some games like GTA Vice City use P8 for texturing which
1529 * conflicts with this.
1531 if( !(GL_SUPPORT(EXT_PALETTED_TEXTURE) || (GL_SUPPORT(ARB_FRAGMENT_PROGRAM) && primary_render_target_is_p8(device))) || colorkey_active || !use_texturing ) {
1532 *format = GL_RGBA;
1533 *internal = GL_RGBA;
1534 *type = GL_UNSIGNED_BYTE;
1535 *target_bpp = 4;
1536 if(colorkey_active) {
1537 *convert = CONVERT_PALETTED_CK;
1538 } else {
1539 *convert = CONVERT_PALETTED;
1542 else if(!GL_SUPPORT(EXT_PALETTED_TEXTURE) && GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
1543 *format = GL_ALPHA;
1544 *internal = GL_RGBA;
1545 *type = GL_UNSIGNED_BYTE;
1546 *target_bpp = 1;
1549 break;
1551 case WINED3DFMT_R3G3B2:
1552 /* **********************
1553 GL_UNSIGNED_BYTE_3_3_2
1554 ********************** */
1555 if (colorkey_active) {
1556 /* This texture format will never be used.. So do not care about color keying
1557 up until the point in time it will be needed :-) */
1558 FIXME(" ColorKeying not supported in the RGB 332 format !\n");
1560 break;
1562 case WINED3DFMT_R5G6B5:
1563 if (colorkey_active) {
1564 *convert = CONVERT_CK_565;
1565 *format = GL_RGBA;
1566 *internal = GL_RGBA;
1567 *type = GL_UNSIGNED_SHORT_5_5_5_1;
1569 break;
1571 case WINED3DFMT_X1R5G5B5:
1572 if (colorkey_active) {
1573 *convert = CONVERT_CK_5551;
1574 *format = GL_BGRA;
1575 *internal = GL_RGBA;
1576 *type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
1578 break;
1580 case WINED3DFMT_R8G8B8:
1581 if (colorkey_active) {
1582 *convert = CONVERT_CK_RGB24;
1583 *format = GL_RGBA;
1584 *internal = GL_RGBA;
1585 *type = GL_UNSIGNED_INT_8_8_8_8;
1586 *target_bpp = 4;
1588 break;
1590 case WINED3DFMT_X8R8G8B8:
1591 if (colorkey_active) {
1592 *convert = CONVERT_RGB32_888;
1593 *format = GL_RGBA;
1594 *internal = GL_RGBA;
1595 *type = GL_UNSIGNED_INT_8_8_8_8;
1597 break;
1599 case WINED3DFMT_V8U8:
1600 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1601 else if(GL_SUPPORT(ATI_ENVMAP_BUMPMAP)) {
1602 *format = GL_DUDV_ATI;
1603 *internal = GL_DU8DV8_ATI;
1604 *type = GL_BYTE;
1605 /* No conversion - Just change the gl type */
1606 break;
1608 *convert = CONVERT_V8U8;
1609 *format = GL_BGR;
1610 *internal = GL_RGB8;
1611 *type = GL_UNSIGNED_BYTE;
1612 *target_bpp = 3;
1613 break;
1615 case WINED3DFMT_L6V5U5:
1616 *convert = CONVERT_L6V5U5;
1617 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1618 *target_bpp = 3;
1619 /* Use format and types from table */
1620 } else {
1621 /* Load it into unsigned R5G6B5, swap L and V channels, and revert that in the shader */
1622 *target_bpp = 2;
1623 *format = GL_RGB;
1624 *internal = GL_RGB5;
1625 *type = GL_UNSIGNED_SHORT_5_6_5;
1627 break;
1629 case WINED3DFMT_X8L8V8U8:
1630 *convert = CONVERT_X8L8V8U8;
1631 *target_bpp = 4;
1632 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1633 /* Use formats from gl table. It is a bit unfortunate, but the conversion
1634 * is needed to set the X format to 255 to get 1.0 for alpha when sampling
1635 * the texture. OpenGL can't use GL_DSDT8_MAG8_NV as internal format with
1636 * the needed type and format parameter, so the internal format contains a
1637 * 4th component, which is returned as alpha
1639 } else {
1640 /* Not supported by GL_ATI_envmap_bumpmap */
1641 *format = GL_BGRA;
1642 *internal = GL_RGB8;
1643 *type = GL_UNSIGNED_INT_8_8_8_8_REV;
1645 break;
1647 case WINED3DFMT_Q8W8V8U8:
1648 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1649 *convert = CONVERT_Q8W8V8U8;
1650 *format = GL_BGRA;
1651 *internal = GL_RGBA8;
1652 *type = GL_UNSIGNED_BYTE;
1653 *target_bpp = 4;
1654 /* Not supported by GL_ATI_envmap_bumpmap */
1655 break;
1657 case WINED3DFMT_V16U16:
1658 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1659 *convert = CONVERT_V16U16;
1660 *format = GL_BGR;
1661 *internal = GL_RGB16_EXT;
1662 *type = GL_UNSIGNED_SHORT;
1663 *target_bpp = 6;
1664 /* What should I do here about GL_ATI_envmap_bumpmap?
1665 * Convert it or allow data loss by loading it into a 8 bit / channel texture?
1667 break;
1669 case WINED3DFMT_A4L4:
1670 /* A4L4 exists as an internal gl format, but for some reason there is not
1671 * format+type combination to load it. Thus convert it to A8L8, then load it
1672 * with A4L4 internal, but A8L8 format+type
1674 *convert = CONVERT_A4L4;
1675 *format = GL_LUMINANCE_ALPHA;
1676 *internal = GL_LUMINANCE4_ALPHA4;
1677 *type = GL_UNSIGNED_BYTE;
1678 *target_bpp = 2;
1679 break;
1681 case WINED3DFMT_R32F:
1682 /* Can be loaded in theory with fmt=GL_RED, type=GL_FLOAT, but this fails. The reason
1683 * is that D3D expects the undefined green, blue and alpha channels to return 1.0
1684 * when sampling, but OpenGL sets green and blue to 0.0 instead. Thus we have to inject
1685 * 1.0 instead.
1687 * The alpha channel defaults to 1.0 in opengl, so nothing has to be done about it.
1689 *convert = CONVERT_R32F;
1690 *format = GL_RGB;
1691 *internal = GL_RGB32F_ARB;
1692 *type = GL_FLOAT;
1693 *target_bpp = 12;
1694 break;
1696 case WINED3DFMT_R16F:
1697 /* Similar to R32F */
1698 *convert = CONVERT_R16F;
1699 *format = GL_RGB;
1700 *internal = GL_RGB16F_ARB;
1701 *type = GL_HALF_FLOAT_ARB;
1702 *target_bpp = 6;
1703 break;
1705 case WINED3DFMT_G16R16:
1706 *convert = CONVERT_G16R16;
1707 *format = GL_RGB;
1708 *internal = GL_RGB16_EXT;
1709 *type = GL_UNSIGNED_SHORT;
1710 *target_bpp = 6;
1711 break;
1713 default:
1714 break;
1717 return WINED3D_OK;
1720 HRESULT d3dfmt_convert_surface(BYTE *src, BYTE *dst, UINT pitch, UINT width, UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *This) {
1721 BYTE *source, *dest;
1722 TRACE("(%p)->(%p),(%d,%d,%d,%d,%p)\n", src, dst, pitch, height, outpitch, convert,This);
1724 switch (convert) {
1725 case NO_CONVERSION:
1727 memcpy(dst, src, pitch * height);
1728 break;
1730 case CONVERT_PALETTED:
1731 case CONVERT_PALETTED_CK:
1733 IWineD3DPaletteImpl* pal = This->palette;
1734 BYTE table[256][4];
1735 unsigned int x, y;
1737 if( pal == NULL) {
1738 /* TODO: If we are a sublevel, try to get the palette from level 0 */
1741 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
1743 for (y = 0; y < height; y++)
1745 source = src + pitch * y;
1746 dest = dst + outpitch * y;
1747 /* This is an 1 bpp format, using the width here is fine */
1748 for (x = 0; x < width; x++) {
1749 BYTE color = *source++;
1750 *dest++ = table[color][0];
1751 *dest++ = table[color][1];
1752 *dest++ = table[color][2];
1753 *dest++ = table[color][3];
1757 break;
1759 case CONVERT_CK_565:
1761 /* Converting the 565 format in 5551 packed to emulate color-keying.
1763 Note : in all these conversion, it would be best to average the averaging
1764 pixels to get the color of the pixel that will be color-keyed to
1765 prevent 'color bleeding'. This will be done later on if ever it is
1766 too visible.
1768 Note2: Nvidia documents say that their driver does not support alpha + color keying
1769 on the same surface and disables color keying in such a case
1771 unsigned int x, y;
1772 WORD *Source;
1773 WORD *Dest;
1775 TRACE("Color keyed 565\n");
1777 for (y = 0; y < height; y++) {
1778 Source = (WORD *) (src + y * pitch);
1779 Dest = (WORD *) (dst + y * outpitch);
1780 for (x = 0; x < width; x++ ) {
1781 WORD color = *Source++;
1782 *Dest = ((color & 0xFFC0) | ((color & 0x1F) << 1));
1783 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1784 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1785 *Dest |= 0x0001;
1787 Dest++;
1791 break;
1793 case CONVERT_CK_5551:
1795 /* Converting X1R5G5B5 format to R5G5B5A1 to emulate color-keying. */
1796 unsigned int x, y;
1797 WORD *Source;
1798 WORD *Dest;
1799 TRACE("Color keyed 5551\n");
1800 for (y = 0; y < height; y++) {
1801 Source = (WORD *) (src + y * pitch);
1802 Dest = (WORD *) (dst + y * outpitch);
1803 for (x = 0; x < width; x++ ) {
1804 WORD color = *Source++;
1805 *Dest = color;
1806 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1807 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1808 *Dest |= (1 << 15);
1810 else {
1811 *Dest &= ~(1 << 15);
1813 Dest++;
1817 break;
1819 case CONVERT_RGB32_888:
1821 /* Converting X8R8G8B8 format to R8G8B8A8 with color-keying. */
1822 unsigned int x, y;
1823 for (y = 0; y < height; y++)
1825 source = src + pitch * y;
1826 dest = dst + outpitch * y;
1827 for (x = 0; x < width; x++) {
1828 DWORD color = 0xffffff & *(DWORD*)source;
1829 DWORD dstcolor = color << 8;
1830 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1831 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1832 dstcolor |= 0xff;
1834 *(DWORD*)dest = dstcolor;
1835 source += 4;
1836 dest += 4;
1840 break;
1842 case CONVERT_V8U8:
1844 unsigned int x, y;
1845 short *Source;
1846 unsigned char *Dest;
1847 for(y = 0; y < height; y++) {
1848 Source = (short *) (src + y * pitch);
1849 Dest = dst + y * outpitch;
1850 for (x = 0; x < width; x++ ) {
1851 long color = (*Source++);
1852 /* B */ Dest[0] = 0xff;
1853 /* G */ Dest[1] = (color >> 8) + 128; /* V */
1854 /* R */ Dest[2] = (color) + 128; /* U */
1855 Dest += 3;
1858 break;
1861 case CONVERT_V16U16:
1863 unsigned int x, y;
1864 DWORD *Source;
1865 unsigned short *Dest;
1866 for(y = 0; y < height; y++) {
1867 Source = (DWORD *) (src + y * pitch);
1868 Dest = (unsigned short *) (dst + y * outpitch);
1869 for (x = 0; x < width; x++ ) {
1870 DWORD color = (*Source++);
1871 /* B */ Dest[0] = 0xffff;
1872 /* G */ Dest[1] = (color >> 16) + 32768; /* V */
1873 /* R */ Dest[2] = (color ) + 32768; /* U */
1874 Dest += 3;
1877 break;
1880 case CONVERT_Q8W8V8U8:
1882 unsigned int x, y;
1883 DWORD *Source;
1884 unsigned char *Dest;
1885 for(y = 0; y < height; y++) {
1886 Source = (DWORD *) (src + y * pitch);
1887 Dest = dst + y * outpitch;
1888 for (x = 0; x < width; x++ ) {
1889 long color = (*Source++);
1890 /* B */ Dest[0] = ((color >> 16) & 0xff) + 128; /* W */
1891 /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
1892 /* R */ Dest[2] = (color & 0xff) + 128; /* U */
1893 /* A */ Dest[3] = ((color >> 24) & 0xff) + 128; /* Q */
1894 Dest += 4;
1897 break;
1900 case CONVERT_L6V5U5:
1902 unsigned int x, y;
1903 WORD *Source;
1904 unsigned char *Dest;
1906 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1907 /* This makes the gl surface bigger(24 bit instead of 16), but it works with
1908 * fixed function and shaders without further conversion once the surface is
1909 * loaded
1911 for(y = 0; y < height; y++) {
1912 Source = (WORD *) (src + y * pitch);
1913 Dest = dst + y * outpitch;
1914 for (x = 0; x < width; x++ ) {
1915 short color = (*Source++);
1916 unsigned char l = ((color >> 10) & 0xfc);
1917 char v = ((color >> 5) & 0x3e);
1918 char u = ((color ) & 0x1f);
1920 /* 8 bits destination, 6 bits source, 8th bit is the sign. gl ignores the sign
1921 * and doubles the positive range. Thus shift left only once, gl does the 2nd
1922 * shift. GL reads a signed value and converts it into an unsigned value.
1924 /* M */ Dest[2] = l << 1;
1926 /* Those are read as signed, but kept signed. Just left-shift 3 times to scale
1927 * from 5 bit values to 8 bit values.
1929 /* V */ Dest[1] = v << 3;
1930 /* U */ Dest[0] = u << 3;
1931 Dest += 3;
1934 } else {
1935 for(y = 0; y < height; y++) {
1936 unsigned short *Dest_s = (unsigned short *) (dst + y * outpitch);
1937 Source = (WORD *) (src + y * pitch);
1938 for (x = 0; x < width; x++ ) {
1939 short color = (*Source++);
1940 unsigned char l = ((color >> 10) & 0xfc);
1941 short v = ((color >> 5) & 0x3e);
1942 short u = ((color ) & 0x1f);
1943 short v_conv = v + 16;
1944 short u_conv = u + 16;
1946 *Dest_s = ((v_conv << 11) & 0xf800) | ((l << 5) & 0x7e0) | (u_conv & 0x1f);
1947 Dest_s += 1;
1951 break;
1954 case CONVERT_X8L8V8U8:
1956 unsigned int x, y;
1957 DWORD *Source;
1958 unsigned char *Dest;
1960 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1961 /* This implementation works with the fixed function pipeline and shaders
1962 * without further modification after converting the surface.
1964 for(y = 0; y < height; y++) {
1965 Source = (DWORD *) (src + y * pitch);
1966 Dest = dst + y * outpitch;
1967 for (x = 0; x < width; x++ ) {
1968 long color = (*Source++);
1969 /* L */ Dest[2] = ((color >> 16) & 0xff); /* L */
1970 /* V */ Dest[1] = ((color >> 8 ) & 0xff); /* V */
1971 /* U */ Dest[0] = (color & 0xff); /* U */
1972 /* I */ Dest[3] = 255; /* X */
1973 Dest += 4;
1976 } else {
1977 /* Doesn't work correctly with the fixed function pipeline, but can work in
1978 * shaders if the shader is adjusted. (There's no use for this format in gl's
1979 * standard fixed function pipeline anyway).
1981 for(y = 0; y < height; y++) {
1982 Source = (DWORD *) (src + y * pitch);
1983 Dest = dst + y * outpitch;
1984 for (x = 0; x < width; x++ ) {
1985 long color = (*Source++);
1986 /* B */ Dest[0] = ((color >> 16) & 0xff); /* L */
1987 /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
1988 /* R */ Dest[2] = (color & 0xff) + 128; /* U */
1989 Dest += 4;
1993 break;
1996 case CONVERT_A4L4:
1998 unsigned int x, y;
1999 unsigned char *Source;
2000 unsigned char *Dest;
2001 for(y = 0; y < height; y++) {
2002 Source = src + y * pitch;
2003 Dest = dst + y * outpitch;
2004 for (x = 0; x < width; x++ ) {
2005 unsigned char color = (*Source++);
2006 /* A */ Dest[1] = (color & 0xf0) << 0;
2007 /* L */ Dest[0] = (color & 0x0f) << 4;
2008 Dest += 2;
2011 break;
2014 case CONVERT_R32F:
2016 unsigned int x, y;
2017 float *Source;
2018 float *Dest;
2019 for(y = 0; y < height; y++) {
2020 Source = (float *) (src + y * pitch);
2021 Dest = (float *) (dst + y * outpitch);
2022 for (x = 0; x < width; x++ ) {
2023 float color = (*Source++);
2024 Dest[0] = color;
2025 Dest[1] = 1.0;
2026 Dest[2] = 1.0;
2027 Dest += 3;
2030 break;
2033 case CONVERT_R16F:
2035 unsigned int x, y;
2036 WORD *Source;
2037 WORD *Dest;
2038 WORD one = 0x3c00;
2039 for(y = 0; y < height; y++) {
2040 Source = (WORD *) (src + y * pitch);
2041 Dest = (WORD *) (dst + y * outpitch);
2042 for (x = 0; x < width; x++ ) {
2043 WORD color = (*Source++);
2044 Dest[0] = color;
2045 Dest[1] = one;
2046 Dest[2] = one;
2047 Dest += 3;
2050 break;
2053 case CONVERT_G16R16:
2055 unsigned int x, y;
2056 WORD *Source;
2057 WORD *Dest;
2059 for(y = 0; y < height; y++) {
2060 Source = (WORD *) (src + y * pitch);
2061 Dest = (WORD *) (dst + y * outpitch);
2062 for (x = 0; x < width; x++ ) {
2063 WORD green = (*Source++);
2064 WORD red = (*Source++);
2065 Dest[0] = green;
2066 Dest[1] = red;
2067 Dest[2] = 0xffff;
2068 Dest += 3;
2071 break;
2074 default:
2075 ERR("Unsupported conversation type %d\n", convert);
2077 return WINED3D_OK;
2080 static void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey) {
2081 IWineD3DPaletteImpl* pal = This->palette;
2082 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2083 BOOL index_in_alpha = FALSE;
2084 int dxVersion = ( (IWineD3DImpl *) device->wineD3D)->dxVersion;
2085 int i;
2087 /* Old games like StarCraft, C&C, Red Alert and others use P8 render targets.
2088 * Reading back the RGB output each lockrect (each frame as they lock the whole screen)
2089 * is slow. Further RGB->P8 conversion is not possible because palettes can have
2090 * duplicate entries. Store the color key in the unused alpha component to speed the
2091 * download up and to make conversion unneeded. */
2092 index_in_alpha = primary_render_target_is_p8(device);
2094 if (pal == NULL) {
2095 /* In DirectDraw the palette is a property of the surface, there are no such things as device palettes. */
2096 if(dxVersion <= 7) {
2097 ERR("This code should never get entered for DirectDraw!, expect problems\n");
2098 if(index_in_alpha) {
2099 /* Guarantees that memory representation remains correct after sysmem<->texture transfers even if
2100 there's no palette at this time. */
2101 for (i = 0; i < 256; i++) table[i][3] = i;
2103 } else {
2104 /* Direct3D >= 8 palette usage style: P8 textures use device palettes, palette entry format is A8R8G8B8,
2105 alpha is stored in peFlags and may be used by the app if D3DPTEXTURECAPS_ALPHAPALETTE device
2106 capability flag is present (wine does advertise this capability) */
2107 for (i = 0; i < 256; i++) {
2108 table[i][0] = device->palettes[device->currentPalette][i].peRed;
2109 table[i][1] = device->palettes[device->currentPalette][i].peGreen;
2110 table[i][2] = device->palettes[device->currentPalette][i].peBlue;
2111 table[i][3] = device->palettes[device->currentPalette][i].peFlags;
2114 } else {
2115 TRACE("Using surface palette %p\n", pal);
2116 /* Get the surface's palette */
2117 for (i = 0; i < 256; i++) {
2118 table[i][0] = pal->palents[i].peRed;
2119 table[i][1] = pal->palents[i].peGreen;
2120 table[i][2] = pal->palents[i].peBlue;
2122 /* When index_in_alpha is the palette index is stored in the alpha component. In case of a readback
2123 we can then read GL_ALPHA. Color keying is handled in BltOverride using a GL_ALPHA_TEST using GL_NOT_EQUAL.
2124 In case of index_in_alpha the color key itself is passed to glAlphaFunc in other cases the alpha component
2125 of pixels that should be masked away is set to 0. */
2126 if(index_in_alpha) {
2127 table[i][3] = i;
2128 } else if(colorkey && (i >= This->SrcBltCKey.dwColorSpaceLowValue) && (i <= This->SrcBltCKey.dwColorSpaceHighValue)) {
2129 table[i][3] = 0x00;
2130 } else if(pal->Flags & WINEDDPCAPS_ALPHA) {
2131 table[i][3] = pal->palents[i].peFlags;
2132 } else {
2133 table[i][3] = 0xFF;
2139 const char *fragment_palette_conversion =
2140 "!!ARBfp1.0\n"
2141 "TEMP index;\n"
2142 "PARAM constants = { 0.996, 0.00195, 0, 0 };\n" /* { 255/256, 0.5/255*255/256, 0, 0 } */
2143 "TEX index, fragment.texcoord[0], texture[0], 2D;\n" /* The alpha-component contains the palette index */
2144 "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 */
2145 "TEX result.color, index.a, texture[1], 1D;\n" /* use the alpha-component as a index in the palette to get the final color */
2146 "END";
2148 /* This function is used in case of 8bit paletted textures to upload the palette.
2149 It supports GL_EXT_paletted_texture and GL_ARB_fragment_program, support for other
2150 extensions like ATI_fragment_shaders is possible.
2152 static void d3dfmt_p8_upload_palette(IWineD3DSurface *iface, CONVERT_TYPES convert) {
2153 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2154 BYTE table[256][4];
2155 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2157 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
2159 /* Try to use the paletted texture extension */
2160 if(GL_SUPPORT(EXT_PALETTED_TEXTURE))
2162 TRACE("Using GL_EXT_PALETTED_TEXTURE for 8-bit paletted texture support\n");
2163 GL_EXTCALL(glColorTableEXT(This->glDescription.target,GL_RGBA,256,GL_RGBA,GL_UNSIGNED_BYTE, table));
2165 else
2167 /* Let a fragment shader do the color conversion by uploading the palette to a 1D texture.
2168 * The 8bit pixel data will be used as an index in this palette texture to retrieve the final color. */
2169 TRACE("Using fragment shaders for emulating 8-bit paletted texture support\n");
2171 /* Create the fragment program if we don't have it */
2172 if(!device->paletteConversionShader)
2174 glEnable(GL_FRAGMENT_PROGRAM_ARB);
2175 GL_EXTCALL(glGenProgramsARB(1, &device->paletteConversionShader));
2176 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, device->paletteConversionShader));
2177 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(fragment_palette_conversion), (const GLbyte *)fragment_palette_conversion));
2178 glDisable(GL_FRAGMENT_PROGRAM_ARB);
2181 glEnable(GL_FRAGMENT_PROGRAM_ARB);
2182 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, device->paletteConversionShader));
2184 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE1));
2185 glEnable(GL_TEXTURE_1D);
2186 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2188 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2189 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); /* Make sure we have discrete color levels. */
2190 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2191 glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, table); /* Upload the palette */
2193 /* Switch back to unit 0 in which the 2D texture will be stored. */
2194 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0));
2196 /* Rebind the texture because it isn't bound anymore */
2197 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2201 BOOL palette9_changed(IWineD3DSurfaceImpl *This) {
2202 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2204 if(This->palette || (This->resource.format != WINED3DFMT_P8 && This->resource.format != WINED3DFMT_A8P8)) {
2205 /* If a ddraw-style palette is attached assume no d3d9 palette change.
2206 * Also the palette isn't interesting if the surface format isn't P8 or A8P8
2208 return FALSE;
2211 if(This->palette9) {
2212 if(memcmp(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256) == 0) {
2213 return FALSE;
2215 } else {
2216 This->palette9 = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
2218 memcpy(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256);
2219 return TRUE;
2222 static inline void clear_unused_channels(IWineD3DSurfaceImpl *This) {
2223 GLboolean oldwrite[4];
2225 /* Some formats have only some color channels, and the others are 1.0.
2226 * since our rendering renders to all channels, and those pixel formats
2227 * are emulated by using a full texture with the other channels set to 1.0
2228 * manually, clear the unused channels.
2230 * This could be done with hacking colorwriteenable to mask the colors,
2231 * but before drawing the buffer would have to be cleared too, so there's
2232 * no gain in that
2234 switch(This->resource.format) {
2235 case WINED3DFMT_R16F:
2236 case WINED3DFMT_R32F:
2237 TRACE("R16F or R32F format, clearing green, blue and alpha to 1.0\n");
2238 /* Do not activate a context, the correct drawable is active already
2239 * though just the read buffer is set, make sure to have the correct draw
2240 * buffer too
2242 glDrawBuffer(This->resource.wineD3DDevice->offscreenBuffer);
2243 glDisable(GL_SCISSOR_TEST);
2244 glGetBooleanv(GL_COLOR_WRITEMASK, oldwrite);
2245 glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_TRUE);
2246 glClearColor(0.0, 1.0, 1.0, 1.0);
2247 glClear(GL_COLOR_BUFFER_BIT);
2248 glColorMask(oldwrite[0], oldwrite[1], oldwrite[2], oldwrite[3]);
2249 if(!This->resource.wineD3DDevice->render_offscreen) glDrawBuffer(GL_BACK);
2250 checkGLcall("Unused channel clear\n");
2251 break;
2253 default: break;
2257 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadTexture(IWineD3DSurface *iface, BOOL srgb_mode) {
2258 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2260 if (!(This->Flags & SFLAG_INTEXTURE)) {
2261 TRACE("Reloading because surface is dirty\n");
2262 } else if(/* Reload: gl texture has ck, now no ckey is set OR */
2263 ((This->Flags & SFLAG_GLCKEY) && (!(This->CKeyFlags & WINEDDSD_CKSRCBLT))) ||
2264 /* Reload: vice versa OR */
2265 ((!(This->Flags & SFLAG_GLCKEY)) && (This->CKeyFlags & WINEDDSD_CKSRCBLT)) ||
2266 /* Also reload: Color key is active AND the color key has changed */
2267 ((This->CKeyFlags & WINEDDSD_CKSRCBLT) && (
2268 (This->glCKey.dwColorSpaceLowValue != This->SrcBltCKey.dwColorSpaceLowValue) ||
2269 (This->glCKey.dwColorSpaceHighValue != This->SrcBltCKey.dwColorSpaceHighValue)))) {
2270 TRACE("Reloading because of color keying\n");
2271 /* To perform the color key conversion we need a sysmem copy of
2272 * the surface. Make sure we have it
2275 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
2276 /* Make sure the texture is reloaded because of the color key change, this kills performance though :( */
2277 /* TODO: This is not necessarily needed with hw palettized texture support */
2278 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2279 } else {
2280 TRACE("surface is already in texture\n");
2281 return WINED3D_OK;
2284 /* Resources are placed in system RAM and do not need to be recreated when a device is lost.
2285 * These resources are not bound by device size or format restrictions. Because of this,
2286 * these resources cannot be accessed by the Direct3D device nor set as textures or render targets.
2287 * However, these resources can always be created, locked, and copied.
2289 if (This->resource.pool == WINED3DPOOL_SCRATCH )
2291 FIXME("(%p) Operation not supported for scratch textures\n",This);
2292 return WINED3DERR_INVALIDCALL;
2295 This->srgb = srgb_mode;
2296 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* no partial locking for textures yet */);
2298 #if 0
2300 static unsigned int gen = 0;
2301 char buffer[4096];
2302 ++gen;
2303 if ((gen % 10) == 0) {
2304 snprintf(buffer, sizeof(buffer), "/tmp/surface%p_type%u_level%u_%u.ppm", This, This->glDescription.target, This->glDescription.level, gen);
2305 IWineD3DSurfaceImpl_SaveSnapshot(iface, buffer);
2308 * debugging crash code
2309 if (gen == 250) {
2310 void** test = NULL;
2311 *test = 0;
2315 #endif
2317 if (!(This->Flags & SFLAG_DONOTFREE)) {
2318 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
2319 This->resource.allocatedMemory = NULL;
2320 This->resource.heapMemory = NULL;
2321 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, FALSE);
2324 return WINED3D_OK;
2327 static void WINAPI IWineD3DSurfaceImpl_BindTexture(IWineD3DSurface *iface) {
2328 /* TODO: check for locks */
2329 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2330 IWineD3DBaseTexture *baseTexture = NULL;
2331 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2333 TRACE("(%p)Checking to see if the container is a base texture\n", This);
2334 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
2335 TRACE("Passing to container\n");
2336 IWineD3DBaseTexture_BindTexture(baseTexture);
2337 IWineD3DBaseTexture_Release(baseTexture);
2338 } else {
2339 TRACE("(%p) : Binding surface\n", This);
2341 if(!device->isInDraw) {
2342 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
2345 ENTER_GL();
2347 glEnable(This->glDescription.target);
2349 if (!This->glDescription.level) {
2350 if (!This->glDescription.textureName) {
2351 glGenTextures(1, &This->glDescription.textureName);
2352 checkGLcall("glGenTextures");
2353 TRACE("Surface %p given name %d\n", This, This->glDescription.textureName);
2355 /* This is where we should be reducing the amount of GLMemoryUsed */
2356 } else if (This->glDescription.textureName) {
2357 /* Mipmap surfaces should have a base texture container */
2358 ERR("Mipmap surface has a glTexture bound to it!\n");
2361 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2362 checkGLcall("glBindTexture");
2364 LEAVE_GL();
2366 return;
2369 #include <errno.h>
2370 #include <stdio.h>
2371 HRESULT WINAPI IWineD3DSurfaceImpl_SaveSnapshot(IWineD3DSurface *iface, const char* filename) {
2372 FILE* f = NULL;
2373 UINT i, y;
2374 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2375 char *allocatedMemory;
2376 char *textureRow;
2377 IWineD3DSwapChain *swapChain = NULL;
2378 int width, height;
2379 GLuint tmpTexture = 0;
2380 DWORD color;
2381 /*FIXME:
2382 Textures may not be stored in ->allocatedgMemory and a GlTexture
2383 so we should lock the surface before saving a snapshot, or at least check that
2385 /* TODO: Compressed texture images can be obtained from the GL in uncompressed form
2386 by calling GetTexImage and in compressed form by calling
2387 GetCompressedTexImageARB. Queried compressed images can be saved and
2388 later reused by calling CompressedTexImage[123]DARB. Pre-compressed
2389 texture images do not need to be processed by the GL and should
2390 significantly improve texture loading performance relative to uncompressed
2391 images. */
2393 /* Setup the width and height to be the internal texture width and height. */
2394 width = This->pow2Width;
2395 height = This->pow2Height;
2396 /* check to see if we're a 'virtual' texture, e.g. we're not a pbuffer of texture, we're a back buffer*/
2397 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapChain);
2399 if (This->Flags & SFLAG_INDRAWABLE && !(This->Flags & SFLAG_INTEXTURE)) {
2400 /* if were not a real texture then read the back buffer into a real texture */
2401 /* we don't want to interfere with the back buffer so read the data into a temporary
2402 * texture and then save the data out of the temporary texture
2404 GLint prevRead;
2405 ENTER_GL();
2406 TRACE("(%p) Reading render target into texture\n", This);
2407 glEnable(GL_TEXTURE_2D);
2409 glGenTextures(1, &tmpTexture);
2410 glBindTexture(GL_TEXTURE_2D, tmpTexture);
2412 glTexImage2D(GL_TEXTURE_2D,
2414 GL_RGBA,
2415 width,
2416 height,
2417 0/*border*/,
2418 GL_RGBA,
2419 GL_UNSIGNED_INT_8_8_8_8_REV,
2420 NULL);
2422 glGetIntegerv(GL_READ_BUFFER, &prevRead);
2423 vcheckGLcall("glGetIntegerv");
2424 glReadBuffer(swapChain ? GL_BACK : This->resource.wineD3DDevice->offscreenBuffer);
2425 vcheckGLcall("glReadBuffer");
2426 glCopyTexImage2D(GL_TEXTURE_2D,
2428 GL_RGBA,
2431 width,
2432 height,
2435 checkGLcall("glCopyTexImage2D");
2436 glReadBuffer(prevRead);
2437 LEAVE_GL();
2439 } else { /* bind the real texture, and make sure it up to date */
2440 IWineD3DSurface_PreLoad(iface);
2442 allocatedMemory = HeapAlloc(GetProcessHeap(), 0, width * height * 4);
2443 ENTER_GL();
2444 FIXME("Saving texture level %d width %d height %d\n", This->glDescription.level, width, height);
2445 glGetTexImage(GL_TEXTURE_2D,
2446 This->glDescription.level,
2447 GL_RGBA,
2448 GL_UNSIGNED_INT_8_8_8_8_REV,
2449 allocatedMemory);
2450 checkGLcall("glTexImage2D");
2451 if (tmpTexture) {
2452 glBindTexture(GL_TEXTURE_2D, 0);
2453 glDeleteTextures(1, &tmpTexture);
2455 LEAVE_GL();
2457 f = fopen(filename, "w+");
2458 if (NULL == f) {
2459 ERR("opening of %s failed with: %s\n", filename, strerror(errno));
2460 return WINED3DERR_INVALIDCALL;
2462 /* Save the data out to a TGA file because 1: it's an easy raw format, 2: it supports an alpha channel */
2463 TRACE("(%p) opened %s with format %s\n", This, filename, debug_d3dformat(This->resource.format));
2464 /* TGA header */
2465 fputc(0,f);
2466 fputc(0,f);
2467 fputc(2,f);
2468 fputc(0,f);
2469 fputc(0,f);
2470 fputc(0,f);
2471 fputc(0,f);
2472 fputc(0,f);
2473 fputc(0,f);
2474 fputc(0,f);
2475 fputc(0,f);
2476 fputc(0,f);
2477 /* short width*/
2478 fwrite(&width,2,1,f);
2479 /* short height */
2480 fwrite(&height,2,1,f);
2481 /* format rgba */
2482 fputc(0x20,f);
2483 fputc(0x28,f);
2484 /* raw data */
2485 /* 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 */
2486 if(swapChain)
2487 textureRow = allocatedMemory + (width * (height - 1) *4);
2488 else
2489 textureRow = allocatedMemory;
2490 for (y = 0 ; y < height; y++) {
2491 for (i = 0; i < width; i++) {
2492 color = *((DWORD*)textureRow);
2493 fputc((color >> 16) & 0xFF, f); /* B */
2494 fputc((color >> 8) & 0xFF, f); /* G */
2495 fputc((color >> 0) & 0xFF, f); /* R */
2496 fputc((color >> 24) & 0xFF, f); /* A */
2497 textureRow += 4;
2499 /* take two rows of the pointer to the texture memory */
2500 if(swapChain)
2501 (textureRow-= width << 3);
2504 TRACE("Closing file\n");
2505 fclose(f);
2507 if(swapChain) {
2508 IWineD3DSwapChain_Release(swapChain);
2510 HeapFree(GetProcessHeap(), 0, allocatedMemory);
2511 return WINED3D_OK;
2515 * Slightly inefficient way to handle multiple dirty rects but it works :)
2517 HRESULT WINAPI IWineD3DSurfaceImpl_AddDirtyRect(IWineD3DSurface *iface, CONST RECT* pDirtyRect) {
2518 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2519 IWineD3DBaseTexture *baseTexture = NULL;
2521 if (!(This->Flags & SFLAG_INSYSMEM) && (This->Flags & SFLAG_INTEXTURE))
2522 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL /* no partial locking for textures yet */);
2524 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2525 if (NULL != pDirtyRect) {
2526 This->dirtyRect.left = min(This->dirtyRect.left, pDirtyRect->left);
2527 This->dirtyRect.top = min(This->dirtyRect.top, pDirtyRect->top);
2528 This->dirtyRect.right = max(This->dirtyRect.right, pDirtyRect->right);
2529 This->dirtyRect.bottom = max(This->dirtyRect.bottom, pDirtyRect->bottom);
2530 } else {
2531 This->dirtyRect.left = 0;
2532 This->dirtyRect.top = 0;
2533 This->dirtyRect.right = This->currentDesc.Width;
2534 This->dirtyRect.bottom = This->currentDesc.Height;
2536 TRACE("(%p) : Dirty: yes, Rect:(%d,%d,%d,%d)\n", This, This->dirtyRect.left,
2537 This->dirtyRect.top, This->dirtyRect.right, This->dirtyRect.bottom);
2538 /* if the container is a basetexture then mark it dirty. */
2539 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
2540 TRACE("Passing to container\n");
2541 IWineD3DBaseTexture_SetDirty(baseTexture, TRUE);
2542 IWineD3DBaseTexture_Release(baseTexture);
2544 return WINED3D_OK;
2547 HRESULT WINAPI IWineD3DSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format) {
2548 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2549 HRESULT hr;
2550 const GlPixelFormatDesc *glDesc;
2551 getFormatDescEntry(format, &GLINFO_LOCATION, &glDesc);
2553 TRACE("(%p) : Calling base function first\n", This);
2554 hr = IWineD3DBaseSurfaceImpl_SetFormat(iface, format);
2555 if(SUCCEEDED(hr)) {
2556 /* Setup some glformat defaults */
2557 This->glDescription.glFormat = glDesc->glFormat;
2558 This->glDescription.glFormatInternal = glDesc->glInternal;
2559 This->glDescription.glType = glDesc->glType;
2561 This->Flags &= ~SFLAG_ALLOCATED;
2562 TRACE("(%p) : glFormat %d, glFotmatInternal %d, glType %d\n", This,
2563 This->glDescription.glFormat, This->glDescription.glFormatInternal, This->glDescription.glType);
2565 return hr;
2568 HRESULT WINAPI IWineD3DSurfaceImpl_SetMem(IWineD3DSurface *iface, void *Mem) {
2569 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
2571 if(This->Flags & (SFLAG_LOCKED | SFLAG_DCINUSE)) {
2572 WARN("Surface is locked or the HDC is in use\n");
2573 return WINED3DERR_INVALIDCALL;
2576 if(Mem && Mem != This->resource.allocatedMemory) {
2577 void *release = NULL;
2579 /* Do I have to copy the old surface content? */
2580 if(This->Flags & SFLAG_DIBSECTION) {
2581 /* Release the DC. No need to hold the critical section for the update
2582 * Thread because this thread runs only on front buffers, but this method
2583 * fails for render targets in the check above.
2585 SelectObject(This->hDC, This->dib.holdbitmap);
2586 DeleteDC(This->hDC);
2587 /* Release the DIB section */
2588 DeleteObject(This->dib.DIBsection);
2589 This->dib.bitmap_data = NULL;
2590 This->resource.allocatedMemory = NULL;
2591 This->hDC = NULL;
2592 This->Flags &= ~SFLAG_DIBSECTION;
2593 } else if(!(This->Flags & SFLAG_USERPTR)) {
2594 release = This->resource.heapMemory;
2595 This->resource.heapMemory = NULL;
2597 This->resource.allocatedMemory = Mem;
2598 This->Flags |= SFLAG_USERPTR | SFLAG_INSYSMEM;
2600 /* Now the surface memory is most up do date. Invalidate drawable and texture */
2601 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2603 /* For client textures opengl has to be notified */
2604 if(This->Flags & SFLAG_CLIENT) {
2605 This->Flags &= ~SFLAG_ALLOCATED;
2606 IWineD3DSurface_PreLoad(iface);
2607 /* And hope that the app behaves correctly and did not free the old surface memory before setting a new pointer */
2610 /* Now free the old memory if any */
2611 HeapFree(GetProcessHeap(), 0, release);
2612 } else if(This->Flags & SFLAG_USERPTR) {
2613 /* LockRect and GetDC will re-create the dib section and allocated memory */
2614 This->resource.allocatedMemory = NULL;
2615 /* HeapMemory should be NULL already */
2616 if(This->resource.heapMemory != NULL) ERR("User pointer surface has heap memory allocated\n");
2617 This->Flags &= ~SFLAG_USERPTR;
2619 if(This->Flags & SFLAG_CLIENT) {
2620 This->Flags &= ~SFLAG_ALLOCATED;
2621 /* This respecifies an empty texture and opengl knows that the old memory is gone */
2622 IWineD3DSurface_PreLoad(iface);
2625 return WINED3D_OK;
2628 void flip_surface(IWineD3DSurfaceImpl *front, IWineD3DSurfaceImpl *back) {
2630 /* Flip the surface contents */
2631 /* Flip the DC */
2633 HDC tmp;
2634 tmp = front->hDC;
2635 front->hDC = back->hDC;
2636 back->hDC = tmp;
2639 /* Flip the DIBsection */
2641 HBITMAP tmp;
2642 BOOL hasDib = front->Flags & SFLAG_DIBSECTION;
2643 tmp = front->dib.DIBsection;
2644 front->dib.DIBsection = back->dib.DIBsection;
2645 back->dib.DIBsection = tmp;
2647 if(back->Flags & SFLAG_DIBSECTION) front->Flags |= SFLAG_DIBSECTION;
2648 else front->Flags &= ~SFLAG_DIBSECTION;
2649 if(hasDib) back->Flags |= SFLAG_DIBSECTION;
2650 else back->Flags &= ~SFLAG_DIBSECTION;
2653 /* Flip the surface data */
2655 void* tmp;
2657 tmp = front->dib.bitmap_data;
2658 front->dib.bitmap_data = back->dib.bitmap_data;
2659 back->dib.bitmap_data = tmp;
2661 tmp = front->resource.allocatedMemory;
2662 front->resource.allocatedMemory = back->resource.allocatedMemory;
2663 back->resource.allocatedMemory = tmp;
2665 tmp = front->resource.heapMemory;
2666 front->resource.heapMemory = back->resource.heapMemory;
2667 back->resource.heapMemory = tmp;
2670 /* Flip the PBO */
2672 GLuint tmp_pbo = front->pbo;
2673 front->pbo = back->pbo;
2674 back->pbo = tmp_pbo;
2677 /* client_memory should not be different, but just in case */
2679 BOOL tmp;
2680 tmp = front->dib.client_memory;
2681 front->dib.client_memory = back->dib.client_memory;
2682 back->dib.client_memory = tmp;
2685 /* Flip the opengl texture */
2687 glDescriptor tmp_desc = back->glDescription;
2688 back->glDescription = front->glDescription;
2689 front->glDescription = tmp_desc;
2693 DWORD tmp_flags = back->Flags;
2694 back->Flags = front->Flags;
2695 front->Flags = tmp_flags;
2699 static HRESULT WINAPI IWineD3DSurfaceImpl_Flip(IWineD3DSurface *iface, IWineD3DSurface *override, DWORD Flags) {
2700 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2701 IWineD3DSwapChainImpl *swapchain = NULL;
2702 HRESULT hr;
2703 TRACE("(%p)->(%p,%x)\n", This, override, Flags);
2705 /* Flipping is only supported on RenderTargets and overlays*/
2706 if( !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_OVERLAY)) ) {
2707 WARN("Tried to flip a non-render target, non-overlay surface\n");
2708 return WINEDDERR_NOTFLIPPABLE;
2711 if(This->resource.usage & WINED3DUSAGE_OVERLAY) {
2712 flip_surface(This, (IWineD3DSurfaceImpl *) override);
2714 /* Update the overlay if it is visible */
2715 if(This->overlay_dest) {
2716 return IWineD3DSurface_DrawOverlay((IWineD3DSurface *) This);
2717 } else {
2718 return WINED3D_OK;
2722 if(override) {
2723 /* DDraw sets this for the X11 surfaces, so don't confuse the user
2724 * FIXME("(%p) Target override is not supported by now\n", This);
2725 * Additionally, it isn't really possible to support triple-buffering
2726 * properly on opengl at all
2730 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **) &swapchain);
2731 if(!swapchain) {
2732 ERR("Flipped surface is not on a swapchain\n");
2733 return WINEDDERR_NOTFLIPPABLE;
2736 /* Just overwrite the swapchain presentation interval. This is ok because only ddraw apps can call Flip,
2737 * and only d3d8 and d3d9 apps specify the presentation interval
2739 if((Flags & (WINEDDFLIP_NOVSYNC | WINEDDFLIP_INTERVAL2 | WINEDDFLIP_INTERVAL3 | WINEDDFLIP_INTERVAL4)) == 0) {
2740 /* Most common case first to avoid wasting time on all the other cases */
2741 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_ONE;
2742 } else if(Flags & WINEDDFLIP_NOVSYNC) {
2743 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
2744 } else if(Flags & WINEDDFLIP_INTERVAL2) {
2745 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_TWO;
2746 } else if(Flags & WINEDDFLIP_INTERVAL3) {
2747 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_THREE;
2748 } else {
2749 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_FOUR;
2752 /* Flipping a OpenGL surface -> Use WineD3DDevice::Present */
2753 hr = IWineD3DSwapChain_Present((IWineD3DSwapChain *) swapchain, NULL, NULL, 0, NULL, 0);
2754 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
2755 return hr;
2758 /* Does a direct frame buffer -> texture copy. Stretching is done
2759 * with single pixel copy calls
2761 static inline void fb_copy_to_texture_direct(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface, IWineD3DSwapChainImpl *swapchain, WINED3DRECT *srect, WINED3DRECT *drect, BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter) {
2762 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2763 float xrel, yrel;
2764 UINT row;
2765 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2768 ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
2769 IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
2770 ENTER_GL();
2772 /* TODO: Do we need GL_TEXTURE_2D enabled fpr copyteximage? */
2773 glEnable(This->glDescription.target);
2774 checkGLcall("glEnable(This->glDescription.target)");
2776 /* Bind the target texture */
2777 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2778 checkGLcall("glBindTexture");
2779 if(!swapchain) {
2780 TRACE("Reading from an offscreen target\n");
2781 upsidedown = !upsidedown;
2782 glReadBuffer(myDevice->offscreenBuffer);
2783 } else {
2784 GLenum buffer = surface_get_gl_buffer(SrcSurface, (IWineD3DSwapChain *)swapchain);
2785 glReadBuffer(buffer);
2787 checkGLcall("glReadBuffer");
2789 xrel = (float) (srect->x2 - srect->x1) / (float) (drect->x2 - drect->x1);
2790 yrel = (float) (srect->y2 - srect->y1) / (float) (drect->y2 - drect->y1);
2792 if( (xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) {
2793 FIXME("Doing a pixel by pixel copy from the framebuffer to a texture, expect major performance issues\n");
2795 if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
2796 ERR("Texture filtering not supported in direct blit\n");
2798 } else if((Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) && ((yrel - 1.0 < -eps) || (yrel - 1.0 > eps))) {
2799 ERR("Texture filtering not supported in direct blit\n");
2802 if(upsidedown &&
2803 !((xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) &&
2804 !((yrel - 1.0 < -eps) || (yrel - 1.0 > eps))) {
2805 /* Upside down copy without stretching is nice, one glCopyTexSubImage call will do */
2807 glCopyTexSubImage2D(This->glDescription.target,
2808 This->glDescription.level,
2809 drect->x1, drect->y1, /* xoffset, yoffset */
2810 srect->x1, Src->currentDesc.Height - srect->y2,
2811 drect->x2 - drect->x1, drect->y2 - drect->y1);
2812 } else {
2813 UINT yoffset = Src->currentDesc.Height - srect->y1 + drect->y1 - 1;
2814 /* I have to process this row by row to swap the image,
2815 * otherwise it would be upside down, so stretching in y direction
2816 * doesn't cost extra time
2818 * However, stretching in x direction can be avoided if not necessary
2820 for(row = drect->y1; row < drect->y2; row++) {
2821 if( (xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) {
2822 /* Well, that stuff works, but it's very slow.
2823 * find a better way instead
2825 UINT col;
2827 for(col = drect->x1; col < drect->x2; col++) {
2828 glCopyTexSubImage2D(This->glDescription.target,
2829 This->glDescription.level,
2830 drect->x1 + col, row, /* xoffset, yoffset */
2831 srect->x1 + col * xrel, yoffset - (int) (row * yrel),
2832 1, 1);
2834 } else {
2835 glCopyTexSubImage2D(This->glDescription.target,
2836 This->glDescription.level,
2837 drect->x1, row, /* xoffset, yoffset */
2838 srect->x1, yoffset - (int) (row * yrel),
2839 drect->x2-drect->x1, 1);
2843 vcheckGLcall("glCopyTexSubImage2D");
2845 /* Leave the opengl state valid for blitting */
2846 glDisable(This->glDescription.target);
2847 checkGLcall("glDisable(This->glDescription.target)");
2849 LEAVE_GL();
2852 /* Uses the hardware to stretch and flip the image */
2853 static inline void fb_copy_to_texture_hwstretch(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface, IWineD3DSwapChainImpl *swapchain, WINED3DRECT *srect, WINED3DRECT *drect, BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter) {
2854 GLuint src, backup = 0;
2855 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2856 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2857 float left, right, top, bottom; /* Texture coordinates */
2858 UINT fbwidth = Src->currentDesc.Width;
2859 UINT fbheight = Src->currentDesc.Height;
2860 GLenum drawBuffer = GL_BACK;
2861 GLenum texture_target;
2862 BOOL noBackBufferBackup;
2864 TRACE("Using hwstretch blit\n");
2865 /* Activate the Proper context for reading from the source surface, set it up for blitting */
2866 ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
2867 IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
2869 noBackBufferBackup = !swapchain && wined3d_settings.offscreen_rendering_mode == ORM_FBO;
2870 if(!noBackBufferBackup && Src->glDescription.textureName == 0) {
2871 /* Get it a description */
2872 IWineD3DSurface_PreLoad(SrcSurface);
2874 ENTER_GL();
2876 /* Try to use an aux buffer for drawing the rectangle. This way it doesn't need restoring.
2877 * This way we don't have to wait for the 2nd readback to finish to leave this function.
2879 if(myDevice->activeContext->aux_buffers >= 2) {
2880 /* Got more than one aux buffer? Use the 2nd aux buffer */
2881 drawBuffer = GL_AUX1;
2882 } else if((swapchain || myDevice->offscreenBuffer == GL_BACK) && myDevice->activeContext->aux_buffers >= 1) {
2883 /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
2884 drawBuffer = GL_AUX0;
2887 if(noBackBufferBackup) {
2888 glGenTextures(1, &backup);
2889 checkGLcall("glGenTextures\n");
2890 glBindTexture(GL_TEXTURE_2D, backup);
2891 checkGLcall("glBindTexture(Src->glDescription.target, Src->glDescription.textureName)");
2892 texture_target = GL_TEXTURE_2D;
2893 } else {
2894 /* Backup the back buffer and copy the source buffer into a texture to draw an upside down stretched quad. If
2895 * we are reading from the back buffer, the backup can be used as source texture
2897 texture_target = Src->glDescription.target;
2898 glBindTexture(texture_target, Src->glDescription.textureName);
2899 checkGLcall("glBindTexture(texture_target, Src->glDescription.textureName)");
2900 glEnable(texture_target);
2901 checkGLcall("glEnable(texture_target)");
2903 /* For now invalidate the texture copy of the back buffer. Drawable and sysmem copy are untouched */
2904 Src->Flags &= ~SFLAG_INTEXTURE;
2907 if(swapchain) {
2908 glReadBuffer(surface_get_gl_buffer(SrcSurface, (IWineD3DSwapChain *)swapchain));
2909 } else {
2910 TRACE("Reading from an offscreen target\n");
2911 upsidedown = !upsidedown;
2912 glReadBuffer(myDevice->offscreenBuffer);
2915 /* TODO: Only back up the part that will be overwritten */
2916 glCopyTexSubImage2D(texture_target, 0,
2917 0, 0 /* read offsets */,
2918 0, 0,
2919 fbwidth,
2920 fbheight);
2922 checkGLcall("glCopyTexSubImage2D");
2924 /* No issue with overriding these - the sampler is dirty due to blit usage */
2925 glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER,
2926 magLookup[Filter - WINED3DTEXF_NONE]);
2927 checkGLcall("glTexParameteri");
2928 glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER,
2929 minMipLookup[Filter][WINED3DTEXF_NONE]);
2930 checkGLcall("glTexParameteri");
2932 if(!swapchain || (IWineD3DSurface *) Src == swapchain->backBuffer[0]) {
2933 src = backup ? backup : Src->glDescription.textureName;
2934 } else {
2935 glReadBuffer(GL_FRONT);
2936 checkGLcall("glReadBuffer(GL_FRONT)");
2938 glGenTextures(1, &src);
2939 checkGLcall("glGenTextures(1, &src)");
2940 glBindTexture(GL_TEXTURE_2D, src);
2941 checkGLcall("glBindTexture(GL_TEXTURE_2D, src)");
2943 /* TODO: Only copy the part that will be read. Use srect->x1, srect->y2 as origin, but with the width watch
2944 * out for power of 2 sizes
2946 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Src->pow2Width, Src->pow2Height, 0,
2947 GL_RGBA, GL_UNSIGNED_BYTE, NULL);
2948 checkGLcall("glTexImage2D");
2949 glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
2950 0, 0 /* read offsets */,
2951 0, 0,
2952 fbwidth,
2953 fbheight);
2955 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2956 checkGLcall("glTexParameteri");
2957 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2958 checkGLcall("glTexParameteri");
2960 glReadBuffer(GL_BACK);
2961 checkGLcall("glReadBuffer(GL_BACK)");
2963 if(texture_target != GL_TEXTURE_2D) {
2964 glDisable(texture_target);
2965 glEnable(GL_TEXTURE_2D);
2966 texture_target = GL_TEXTURE_2D;
2969 checkGLcall("glEnd and previous");
2971 left = srect->x1;
2972 right = srect->x2;
2974 if(upsidedown) {
2975 top = Src->currentDesc.Height - srect->y1;
2976 bottom = Src->currentDesc.Height - srect->y2;
2977 } else {
2978 top = Src->currentDesc.Height - srect->y2;
2979 bottom = Src->currentDesc.Height - srect->y1;
2982 if(Src->Flags & SFLAG_NORMCOORD) {
2983 left /= Src->pow2Width;
2984 right /= Src->pow2Width;
2985 top /= Src->pow2Height;
2986 bottom /= Src->pow2Height;
2989 /* draw the source texture stretched and upside down. The correct surface is bound already */
2990 glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
2991 glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
2993 glDrawBuffer(drawBuffer);
2994 glReadBuffer(drawBuffer);
2996 glBegin(GL_QUADS);
2997 /* bottom left */
2998 glTexCoord2f(left, bottom);
2999 glVertex2i(0, fbheight);
3001 /* top left */
3002 glTexCoord2f(left, top);
3003 glVertex2i(0, fbheight - drect->y2 - drect->y1);
3005 /* top right */
3006 glTexCoord2f(right, top);
3007 glVertex2i(drect->x2 - drect->x1, fbheight - drect->y2 - drect->y1);
3009 /* bottom right */
3010 glTexCoord2f(right, bottom);
3011 glVertex2i(drect->x2 - drect->x1, fbheight);
3012 glEnd();
3013 checkGLcall("glEnd and previous");
3015 if(texture_target != This->glDescription.target) {
3016 glDisable(texture_target);
3017 glEnable(This->glDescription.target);
3018 texture_target = This->glDescription.target;
3021 /* Now read the stretched and upside down image into the destination texture */
3022 glBindTexture(texture_target, This->glDescription.textureName);
3023 checkGLcall("glBindTexture");
3024 glCopyTexSubImage2D(texture_target,
3026 drect->x1, drect->y1, /* xoffset, yoffset */
3027 0, 0, /* We blitted the image to the origin */
3028 drect->x2 - drect->x1, drect->y2 - drect->y1);
3029 checkGLcall("glCopyTexSubImage2D");
3031 if(drawBuffer == GL_BACK) {
3032 /* Write the back buffer backup back */
3033 if(backup) {
3034 if(texture_target != GL_TEXTURE_2D) {
3035 glDisable(texture_target);
3036 glEnable(GL_TEXTURE_2D);
3037 texture_target = GL_TEXTURE_2D;
3039 glBindTexture(GL_TEXTURE_2D, backup);
3040 checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
3041 } else {
3042 if(texture_target != Src->glDescription.target) {
3043 glDisable(texture_target);
3044 glEnable(Src->glDescription.target);
3045 texture_target = Src->glDescription.target;
3047 glBindTexture(Src->glDescription.target, Src->glDescription.textureName);
3048 checkGLcall("glBindTexture(Src->glDescription.target, Src->glDescription.textureName)");
3051 glBegin(GL_QUADS);
3052 /* top left */
3053 glTexCoord2f(0.0, (float) fbheight / (float) Src->pow2Height);
3054 glVertex2i(0, 0);
3056 /* bottom left */
3057 glTexCoord2f(0.0, 0.0);
3058 glVertex2i(0, fbheight);
3060 /* bottom right */
3061 glTexCoord2f((float) fbwidth / (float) Src->pow2Width, 0.0);
3062 glVertex2i(fbwidth, Src->currentDesc.Height);
3064 /* top right */
3065 glTexCoord2f((float) fbwidth / (float) Src->pow2Width, (float) fbheight / (float) Src->pow2Height);
3066 glVertex2i(fbwidth, 0);
3067 glEnd();
3068 } else {
3069 /* Restore the old draw buffer */
3070 glDrawBuffer(GL_BACK);
3072 glDisable(texture_target);
3073 checkGLcall("glDisable(texture_target)");
3075 /* Cleanup */
3076 if(src != Src->glDescription.textureName && src != backup) {
3077 glDeleteTextures(1, &src);
3078 checkGLcall("glDeleteTextures(1, &src)");
3080 if(backup) {
3081 glDeleteTextures(1, &backup);
3082 checkGLcall("glDeleteTextures(1, &backup)");
3085 LEAVE_GL();
3088 /* Not called from the VTable */
3089 static HRESULT IWineD3DSurfaceImpl_BltOverride(IWineD3DSurfaceImpl *This, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
3090 WINED3DRECT rect;
3091 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3092 IWineD3DSwapChainImpl *srcSwapchain = NULL, *dstSwapchain = NULL;
3093 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
3095 TRACE("(%p)->(%p,%p,%p,%08x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3097 /* Get the swapchain. One of the surfaces has to be a primary surface */
3098 if(This->resource.pool == WINED3DPOOL_SYSTEMMEM) {
3099 WARN("Destination is in sysmem, rejecting gl blt\n");
3100 return WINED3DERR_INVALIDCALL;
3102 IWineD3DSurface_GetContainer( (IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&dstSwapchain);
3103 if(dstSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) dstSwapchain);
3104 if(Src) {
3105 if(Src->resource.pool == WINED3DPOOL_SYSTEMMEM) {
3106 WARN("Src is in sysmem, rejecting gl blt\n");
3107 return WINED3DERR_INVALIDCALL;
3109 IWineD3DSurface_GetContainer( (IWineD3DSurface *) Src, &IID_IWineD3DSwapChain, (void **)&srcSwapchain);
3110 if(srcSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) srcSwapchain);
3113 /* Early sort out of cases where no render target is used */
3114 if(!dstSwapchain && !srcSwapchain &&
3115 SrcSurface != myDevice->render_targets[0] && This != (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
3116 TRACE("No surface is render target, not using hardware blit. Src = %p, dst = %p\n", Src, This);
3117 return WINED3DERR_INVALIDCALL;
3120 /* No destination color keying supported */
3121 if(Flags & (WINEDDBLT_KEYDEST | WINEDDBLT_KEYDESTOVERRIDE)) {
3122 /* Can we support that with glBlendFunc if blitting to the frame buffer? */
3123 TRACE("Destination color key not supported in accelerated Blit, falling back to software\n");
3124 return WINED3DERR_INVALIDCALL;
3127 if (DestRect) {
3128 rect.x1 = DestRect->left;
3129 rect.y1 = DestRect->top;
3130 rect.x2 = DestRect->right;
3131 rect.y2 = DestRect->bottom;
3132 } else {
3133 rect.x1 = 0;
3134 rect.y1 = 0;
3135 rect.x2 = This->currentDesc.Width;
3136 rect.y2 = This->currentDesc.Height;
3139 /* The only case where both surfaces on a swapchain are supported is a back buffer -> front buffer blit on the same swapchain */
3140 if(dstSwapchain && dstSwapchain == srcSwapchain && dstSwapchain->backBuffer &&
3141 ((IWineD3DSurface *) This == dstSwapchain->frontBuffer) && SrcSurface == dstSwapchain->backBuffer[0]) {
3142 /* Half-life does a Blt from the back buffer to the front buffer,
3143 * Full surface size, no flags... Use present instead
3145 * This path will only be entered for d3d7 and ddraw apps, because d3d8/9 offer no way to blit TO the front buffer
3148 /* Check rects - IWineD3DDevice_Present doesn't handle them */
3149 while(1)
3151 RECT mySrcRect;
3152 TRACE("Looking if a Present can be done...\n");
3153 /* Source Rectangle must be full surface */
3154 if( SrcRect ) {
3155 if(SrcRect->left != 0 || SrcRect->top != 0 ||
3156 SrcRect->right != Src->currentDesc.Width || SrcRect->bottom != Src->currentDesc.Height) {
3157 TRACE("No, Source rectangle doesn't match\n");
3158 break;
3161 mySrcRect.left = 0;
3162 mySrcRect.top = 0;
3163 mySrcRect.right = Src->currentDesc.Width;
3164 mySrcRect.bottom = Src->currentDesc.Height;
3166 /* No stretching may occur */
3167 if(mySrcRect.right != rect.x2 - rect.x1 ||
3168 mySrcRect.bottom != rect.y2 - rect.y1) {
3169 TRACE("No, stretching is done\n");
3170 break;
3173 /* Destination must be full surface or match the clipping rectangle */
3174 if(This->clipper && ((IWineD3DClipperImpl *) This->clipper)->hWnd)
3176 RECT cliprect;
3177 POINT pos[2];
3178 GetClientRect(((IWineD3DClipperImpl *) This->clipper)->hWnd, &cliprect);
3179 pos[0].x = rect.x1;
3180 pos[0].y = rect.y1;
3181 pos[1].x = rect.x2;
3182 pos[1].y = rect.y2;
3183 MapWindowPoints(GetDesktopWindow(), ((IWineD3DClipperImpl *) This->clipper)->hWnd,
3184 pos, 2);
3186 if(pos[0].x != cliprect.left || pos[0].y != cliprect.top ||
3187 pos[1].x != cliprect.right || pos[1].y != cliprect.bottom)
3189 TRACE("No, dest rectangle doesn't match(clipper)\n");
3190 TRACE("Clip rect at (%d,%d)-(%d,%d)\n", cliprect.left, cliprect.top, cliprect.right, cliprect.bottom);
3191 TRACE("Blt dest: (%d,%d)-(%d,%d)\n", rect.x1, rect.y1, rect.x2, rect.y2);
3192 break;
3195 else
3197 if(rect.x1 != 0 || rect.y1 != 0 ||
3198 rect.x2 != This->currentDesc.Width || rect.y2 != This->currentDesc.Height) {
3199 TRACE("No, dest rectangle doesn't match(surface size)\n");
3200 break;
3204 TRACE("Yes\n");
3206 /* These flags are unimportant for the flag check, remove them */
3207 if((Flags & ~(WINEDDBLT_DONOTWAIT | WINEDDBLT_WAIT)) == 0) {
3208 WINED3DSWAPEFFECT orig_swap = dstSwapchain->presentParms.SwapEffect;
3210 /* The idea behind this is that a glReadPixels and a glDrawPixels call
3211 * take very long, while a flip is fast.
3212 * This applies to Half-Life, which does such Blts every time it finished
3213 * a frame, and to Prince of Persia 3D, which uses this to draw at least the main
3214 * menu. This is also used by all apps when they do windowed rendering
3216 * The problem is that flipping is not really the same as copying. After a
3217 * Blt the front buffer is a copy of the back buffer, and the back buffer is
3218 * untouched. Therefore it's necessary to override the swap effect
3219 * and to set it back after the flip.
3221 * Windowed Direct3D < 7 apps do the same. The D3D7 sdk demos are nice
3222 * testcases.
3225 dstSwapchain->presentParms.SwapEffect = WINED3DSWAPEFFECT_COPY;
3226 dstSwapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
3228 TRACE("Full screen back buffer -> front buffer blt, performing a flip instead\n");
3229 IWineD3DSwapChain_Present((IWineD3DSwapChain *) dstSwapchain, NULL, NULL, 0, NULL, 0);
3231 dstSwapchain->presentParms.SwapEffect = orig_swap;
3233 return WINED3D_OK;
3235 break;
3238 TRACE("Unsupported blit between buffers on the same swapchain\n");
3239 return WINED3DERR_INVALIDCALL;
3240 } else if(dstSwapchain && dstSwapchain == srcSwapchain) {
3241 FIXME("Implement hardware blit between two surfaces on the same swapchain\n");
3242 return WINED3DERR_INVALIDCALL;
3243 } else if(dstSwapchain && srcSwapchain) {
3244 FIXME("Implement hardware blit between two different swapchains\n");
3245 return WINED3DERR_INVALIDCALL;
3246 } else if(dstSwapchain) {
3247 if(SrcSurface == myDevice->render_targets[0]) {
3248 TRACE("Blit from active render target to a swapchain\n");
3249 /* Handled with regular texture -> swapchain blit */
3251 } else if(srcSwapchain && This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
3252 FIXME("Implement blit from a swapchain to the active render target\n");
3253 return WINED3DERR_INVALIDCALL;
3256 if((srcSwapchain || SrcSurface == myDevice->render_targets[0]) && !dstSwapchain) {
3257 /* Blit from render target to texture */
3258 WINED3DRECT srect;
3259 BOOL upsideDown, stretchx;
3260 BOOL paletteOverride = FALSE;
3262 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3263 TRACE("Color keying not supported by frame buffer to texture blit\n");
3264 return WINED3DERR_INVALIDCALL;
3265 /* Destination color key is checked above */
3268 /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
3269 * glCopyTexSubImage is a bit picky about the parameters we pass to it
3271 if(SrcRect) {
3272 if(SrcRect->top < SrcRect->bottom) {
3273 srect.y1 = SrcRect->top;
3274 srect.y2 = SrcRect->bottom;
3275 upsideDown = FALSE;
3276 } else {
3277 srect.y1 = SrcRect->bottom;
3278 srect.y2 = SrcRect->top;
3279 upsideDown = TRUE;
3281 srect.x1 = SrcRect->left;
3282 srect.x2 = SrcRect->right;
3283 } else {
3284 srect.x1 = 0;
3285 srect.y1 = 0;
3286 srect.x2 = Src->currentDesc.Width;
3287 srect.y2 = Src->currentDesc.Height;
3288 upsideDown = FALSE;
3290 if(rect.x1 > rect.x2) {
3291 UINT tmp = rect.x2;
3292 rect.x2 = rect.x1;
3293 rect.x1 = tmp;
3294 upsideDown = !upsideDown;
3297 if(rect.x2 - rect.x1 != srect.x2 - srect.x1) {
3298 stretchx = TRUE;
3299 } else {
3300 stretchx = FALSE;
3303 /* When blitting from a render target a texture, the texture isn't required to have a palette.
3304 * In this case grab the palette from the render target. */
3305 if((This->resource.format == WINED3DFMT_P8) && (This->palette == NULL)) {
3306 paletteOverride = TRUE;
3307 TRACE("Source surface (%p) lacks palette, overriding palette with palette %p of destination surface (%p)\n", Src, This->palette, This);
3308 This->palette = Src->palette;
3311 /* Blt is a pretty powerful call, while glCopyTexSubImage2D is not. glCopyTexSubImage cannot
3312 * flip the image nor scale it.
3314 * -> If the app asks for a unscaled, upside down copy, just perform one glCopyTexSubImage2D call
3315 * -> If the app wants a image width an unscaled width, copy it line per line
3316 * -> If the app wants a image that is scaled on the x axis, and the destination rectangle is smaller
3317 * than the frame buffer, draw an upside down scaled image onto the fb, read it back and restore the
3318 * back buffer. This is slower than reading line per line, thus not used for flipping
3319 * -> If the app wants a scaled image with a dest rect that is bigger than the fb, it has to be copied
3320 * pixel by pixel
3322 * If EXT_framebuffer_blit is supported that can be used instead. Note that EXT_framebuffer_blit implies
3323 * FBO support, so it doesn't really make sense to try and make it work with different offscreen rendering
3324 * backends.
3326 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && GL_SUPPORT(EXT_FRAMEBUFFER_BLIT)) {
3327 stretch_rect_fbo((IWineD3DDevice *)myDevice, SrcSurface, &srect,
3328 (IWineD3DSurface *)This, &rect, Filter, upsideDown);
3329 } else if((!stretchx) || rect.x2 - rect.x1 > Src->currentDesc.Width ||
3330 rect.y2 - rect.y1 > Src->currentDesc.Height) {
3331 TRACE("No stretching in x direction, using direct framebuffer -> texture copy\n");
3332 fb_copy_to_texture_direct(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
3333 } else {
3334 TRACE("Using hardware stretching to flip / stretch the texture\n");
3335 fb_copy_to_texture_hwstretch(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
3338 /* Clear the palette as the surface didn't have a palette attached, it would confuse GetPalette and other calls */
3339 if(paletteOverride)
3340 This->palette = NULL;
3342 if(!(This->Flags & SFLAG_DONOTFREE)) {
3343 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
3344 This->resource.allocatedMemory = NULL;
3345 This->resource.heapMemory = NULL;
3346 } else {
3347 This->Flags &= ~SFLAG_INSYSMEM;
3349 /* The texture is now most up to date - If the surface is a render target and has a drawable, this
3350 * path is never entered
3352 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) This, SFLAG_INTEXTURE, TRUE);
3354 return WINED3D_OK;
3355 } else if(Src) {
3356 /* Blit from offscreen surface to render target */
3357 float glTexCoord[4];
3358 DWORD oldCKeyFlags = Src->CKeyFlags;
3359 WINEDDCOLORKEY oldBltCKey = Src->SrcBltCKey;
3360 RECT SourceRectangle;
3361 BOOL paletteOverride = FALSE;
3362 GLenum buffer;
3364 TRACE("Blt from surface %p to rendertarget %p\n", Src, This);
3366 if(SrcRect) {
3367 SourceRectangle.left = SrcRect->left;
3368 SourceRectangle.right = SrcRect->right;
3369 SourceRectangle.top = SrcRect->top;
3370 SourceRectangle.bottom = SrcRect->bottom;
3371 } else {
3372 SourceRectangle.left = 0;
3373 SourceRectangle.right = Src->currentDesc.Width;
3374 SourceRectangle.top = 0;
3375 SourceRectangle.bottom = Src->currentDesc.Height;
3378 /* When blitting from an offscreen surface to a rendertarget, the source
3379 * surface is not required to have a palette. Our rendering / conversion
3380 * code further down the road retrieves the palette from the surface, so
3381 * it must have a palette set. */
3382 if((Src->resource.format == WINED3DFMT_P8) && (Src->palette == NULL)) {
3383 paletteOverride = TRUE;
3384 TRACE("Source surface (%p) lacks palette, overriding palette with palette %p of destination surface (%p)\n", Src, This->palette, This);
3385 Src->palette = This->palette;
3388 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && GL_SUPPORT(EXT_FRAMEBUFFER_BLIT) &&
3389 (Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) == 0) {
3390 TRACE("Using stretch_rect_fbo\n");
3391 /* The source is always a texture, but never the currently active render target, and the texture
3392 * contents are never upside down
3394 stretch_rect_fbo((IWineD3DDevice *)myDevice, SrcSurface, (WINED3DRECT *) &SourceRectangle,
3395 (IWineD3DSurface *)This, &rect, Filter, FALSE);
3397 /* Clear the palette as the surface didn't have a palette attached, it would confuse GetPalette and other calls */
3398 if(paletteOverride)
3399 Src->palette = NULL;
3400 return WINED3D_OK;
3403 if(!CalculateTexRect(Src, &SourceRectangle, glTexCoord)) {
3404 /* Fall back to software */
3405 WARN("(%p) Source texture area (%d,%d)-(%d,%d) is too big\n", Src,
3406 SourceRectangle.left, SourceRectangle.top,
3407 SourceRectangle.right, SourceRectangle.bottom);
3408 return WINED3DERR_INVALIDCALL;
3411 /* Color keying: Check if we have to do a color keyed blt,
3412 * and if not check if a color key is activated.
3414 * Just modify the color keying parameters in the surface and restore them afterwards
3415 * The surface keeps track of the color key last used to load the opengl surface.
3416 * PreLoad will catch the change to the flags and color key and reload if necessary.
3418 if(Flags & WINEDDBLT_KEYSRC) {
3419 /* Use color key from surface */
3420 } else if(Flags & WINEDDBLT_KEYSRCOVERRIDE) {
3421 /* Use color key from DDBltFx */
3422 Src->CKeyFlags |= WINEDDSD_CKSRCBLT;
3423 Src->SrcBltCKey = DDBltFx->ddckSrcColorkey;
3424 } else {
3425 /* Do not use color key */
3426 Src->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
3429 /* Now load the surface */
3430 IWineD3DSurface_PreLoad((IWineD3DSurface *) Src);
3433 /* Activate the destination context, set it up for blitting */
3434 ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
3436 if(!dstSwapchain) {
3437 TRACE("Drawing to offscreen buffer\n");
3438 buffer = myDevice->offscreenBuffer;
3439 } else {
3440 buffer = surface_get_gl_buffer((IWineD3DSurface *)This, (IWineD3DSwapChain *)dstSwapchain);
3442 /* Front buffer coordinates are screen coordinates, while OpenGL coordinates are
3443 * window relative. Also beware of the origin difference(top left vs bottom left).
3444 * Also beware that the front buffer's surface size is screen width x screen height,
3445 * whereas the real gl drawable size is the size of the window.
3447 if(buffer == GL_FRONT) {
3448 RECT windowsize;
3449 POINT offset = {0,0};
3450 UINT h;
3451 ClientToScreen(dstSwapchain->win_handle, &offset);
3452 GetClientRect(dstSwapchain->win_handle, &windowsize);
3453 h = windowsize.bottom - windowsize.top;
3454 rect.x1 -= offset.x; rect.x2 -=offset.x;
3455 rect.y1 -= offset.y; rect.y2 -=offset.y;
3456 rect.y1 += This->currentDesc.Height - h; rect.y2 += This->currentDesc.Height - h;
3458 TRACE("Drawing to %#x buffer\n", buffer);
3461 ENTER_GL();
3462 glDrawBuffer(buffer);
3463 checkGLcall("glDrawBuffer");
3465 myDevice->blitter->set_shader((IWineD3DDevice *) myDevice, Src->resource.format,
3466 Src->glDescription.target, Src->pow2Width, Src->pow2Height);
3468 /* Bind the texture */
3469 glBindTexture(Src->glDescription.target, Src->glDescription.textureName);
3470 checkGLcall("glBindTexture");
3472 /* Filtering for StretchRect */
3473 glTexParameteri(Src->glDescription.target, GL_TEXTURE_MAG_FILTER,
3474 magLookup[Filter - WINED3DTEXF_NONE]);
3475 checkGLcall("glTexParameteri");
3476 glTexParameteri(Src->glDescription.target, GL_TEXTURE_MIN_FILTER,
3477 minMipLookup[Filter][WINED3DTEXF_NONE]);
3478 checkGLcall("glTexParameteri");
3479 glTexParameteri(Src->glDescription.target, GL_TEXTURE_WRAP_S, GL_CLAMP);
3480 glTexParameteri(Src->glDescription.target, GL_TEXTURE_WRAP_T, GL_CLAMP);
3481 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
3482 checkGLcall("glTexEnvi");
3484 /* This is for color keying */
3485 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3486 glEnable(GL_ALPHA_TEST);
3487 checkGLcall("glEnable GL_ALPHA_TEST");
3489 /* When the primary render target uses P8, the alpha component contains the palette index.
3490 * Which means that the colorkey is one of the palette entries. In other cases pixels that
3491 * should be masked away have alpha set to 0. */
3492 if(primary_render_target_is_p8(myDevice))
3493 glAlphaFunc(GL_NOTEQUAL, (float)Src->SrcBltCKey.dwColorSpaceLowValue / 256.0);
3494 else
3495 glAlphaFunc(GL_NOTEQUAL, 0.0);
3496 checkGLcall("glAlphaFunc\n");
3497 } else {
3498 glDisable(GL_ALPHA_TEST);
3499 checkGLcall("glDisable GL_ALPHA_TEST");
3502 /* Draw a textured quad
3504 glBegin(GL_QUADS);
3506 glColor3d(1.0f, 1.0f, 1.0f);
3507 glTexCoord2f(glTexCoord[0], glTexCoord[2]);
3508 glVertex3f(rect.x1,
3509 rect.y1,
3510 0.0);
3512 glTexCoord2f(glTexCoord[0], glTexCoord[3]);
3513 glVertex3f(rect.x1, rect.y2, 0.0);
3515 glTexCoord2f(glTexCoord[1], glTexCoord[3]);
3516 glVertex3f(rect.x2,
3517 rect.y2,
3518 0.0);
3520 glTexCoord2f(glTexCoord[1], glTexCoord[2]);
3521 glVertex3f(rect.x2,
3522 rect.y1,
3523 0.0);
3524 glEnd();
3525 checkGLcall("glEnd");
3527 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3528 glDisable(GL_ALPHA_TEST);
3529 checkGLcall("glDisable(GL_ALPHA_TEST)");
3532 glBindTexture(Src->glDescription.target, 0);
3533 checkGLcall("glBindTexture(Src->glDescription.target, 0)");
3534 /* Leave the opengl state valid for blitting */
3535 myDevice->blitter->unset_shader((IWineD3DDevice *) myDevice);
3537 /* The draw buffer should only need to be restored if we were drawing to the front buffer, and there is a back buffer.
3538 * otherwise the context manager should choose between GL_BACK / offscreenDrawBuffer
3540 if(dstSwapchain && This == (IWineD3DSurfaceImpl *) dstSwapchain->frontBuffer && dstSwapchain->backBuffer) {
3541 glDrawBuffer(GL_BACK);
3542 checkGLcall("glDrawBuffer");
3544 /* Restore the color key parameters */
3545 Src->CKeyFlags = oldCKeyFlags;
3546 Src->SrcBltCKey = oldBltCKey;
3548 /* Clear the palette as the surface didn't have a palette attached, it would confuse GetPalette and other calls */
3549 if(paletteOverride)
3550 Src->palette = NULL;
3552 LEAVE_GL();
3554 /* Flush in case the drawable is used by multiple GL contexts */
3555 if(dstSwapchain && (This == (IWineD3DSurfaceImpl *) dstSwapchain->frontBuffer || dstSwapchain->num_contexts >= 2))
3556 glFlush();
3558 /* TODO: If the surface is locked often, perform the Blt in software on the memory instead */
3559 /* The surface is now in the drawable. On onscreen surfaces or without fbos the texture
3560 * is outdated now
3562 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) This, SFLAG_INDRAWABLE, TRUE);
3563 /* TODO: This should be moved to ModifyLocation() */
3564 if(!(dstSwapchain || wined3d_settings.offscreen_rendering_mode != ORM_FBO)) {
3565 This->Flags |= SFLAG_INTEXTURE;
3568 return WINED3D_OK;
3569 } else {
3570 /* Source-Less Blit to render target */
3571 if (Flags & WINEDDBLT_COLORFILL) {
3572 /* This is easy to handle for the D3D Device... */
3573 DWORD color;
3575 TRACE("Colorfill\n");
3577 /* This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0] || dstSwapchain
3578 must be true if we are here */
3579 if (This != (IWineD3DSurfaceImpl *) myDevice->render_targets[0] &&
3580 !(This == (IWineD3DSurfaceImpl*) dstSwapchain->frontBuffer ||
3581 (dstSwapchain->backBuffer && This == (IWineD3DSurfaceImpl*) dstSwapchain->backBuffer[0]))) {
3582 TRACE("Surface is higher back buffer, falling back to software\n");
3583 return WINED3DERR_INVALIDCALL;
3586 /* The color as given in the Blt function is in the format of the frame-buffer...
3587 * 'clear' expect it in ARGB format => we need to do some conversion :-)
3589 if (This->resource.format == WINED3DFMT_P8) {
3590 DWORD alpha;
3592 if (primary_render_target_is_p8(myDevice)) alpha = DDBltFx->u5.dwFillColor << 24;
3593 else alpha = 0xFF000000;
3595 if (This->palette) {
3596 color = (alpha |
3597 (This->palette->palents[DDBltFx->u5.dwFillColor].peRed << 16) |
3598 (This->palette->palents[DDBltFx->u5.dwFillColor].peGreen << 8) |
3599 (This->palette->palents[DDBltFx->u5.dwFillColor].peBlue));
3600 } else {
3601 color = alpha;
3604 else if (This->resource.format == WINED3DFMT_R5G6B5) {
3605 if (DDBltFx->u5.dwFillColor == 0xFFFF) {
3606 color = 0xFFFFFFFF;
3607 } else {
3608 color = ((0xFF000000) |
3609 ((DDBltFx->u5.dwFillColor & 0xF800) << 8) |
3610 ((DDBltFx->u5.dwFillColor & 0x07E0) << 5) |
3611 ((DDBltFx->u5.dwFillColor & 0x001F) << 3));
3614 else if ((This->resource.format == WINED3DFMT_R8G8B8) ||
3615 (This->resource.format == WINED3DFMT_X8R8G8B8) ) {
3616 color = 0xFF000000 | DDBltFx->u5.dwFillColor;
3618 else if (This->resource.format == WINED3DFMT_A8R8G8B8) {
3619 color = DDBltFx->u5.dwFillColor;
3621 else {
3622 ERR("Wrong surface type for BLT override(Format doesn't match) !\n");
3623 return WINED3DERR_INVALIDCALL;
3626 TRACE("(%p) executing Render Target override, color = %x\n", This, color);
3627 IWineD3DDeviceImpl_ClearSurface(myDevice, This,
3628 1, /* Number of rectangles */
3629 &rect, WINED3DCLEAR_TARGET, color,
3630 0.0 /* Z */,
3631 0 /* Stencil */);
3632 return WINED3D_OK;
3636 /* Default: Fall back to the generic blt. Not an error, a TRACE is enough */
3637 TRACE("Didn't find any usable render target setup for hw blit, falling back to software\n");
3638 return WINED3DERR_INVALIDCALL;
3641 static HRESULT WINAPI IWineD3DSurfaceImpl_BltZ(IWineD3DSurfaceImpl *This, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx)
3643 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3644 float depth;
3646 if (Flags & WINEDDBLT_DEPTHFILL) {
3647 switch(This->resource.format) {
3648 case WINED3DFMT_D16:
3649 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000ffff;
3650 break;
3651 case WINED3DFMT_D15S1:
3652 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000fffe;
3653 break;
3654 case WINED3DFMT_D24S8:
3655 case WINED3DFMT_D24X8:
3656 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00ffffff;
3657 break;
3658 case WINED3DFMT_D32:
3659 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0xffffffff;
3660 break;
3661 default:
3662 depth = 0.0;
3663 ERR("Unexpected format for depth fill: %s\n", debug_d3dformat(This->resource.format));
3666 return IWineD3DDevice_Clear((IWineD3DDevice *) myDevice,
3667 DestRect == NULL ? 0 : 1,
3668 (WINED3DRECT *) DestRect,
3669 WINED3DCLEAR_ZBUFFER,
3670 0x00000000,
3671 depth,
3672 0x00000000);
3675 FIXME("(%p): Unsupp depthstencil blit\n", This);
3676 return WINED3DERR_INVALIDCALL;
3679 static HRESULT WINAPI IWineD3DSurfaceImpl_Blt(IWineD3DSurface *iface, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
3680 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3681 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
3682 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3683 TRACE("(%p)->(%p,%p,%p,%x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3684 TRACE("(%p): Usage is %s\n", This, debug_d3dusage(This->resource.usage));
3686 if ( (This->Flags & SFLAG_LOCKED) || ((Src != NULL) && (Src->Flags & SFLAG_LOCKED)))
3688 WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3689 return WINEDDERR_SURFACEBUSY;
3692 /* Accessing the depth stencil is supposed to fail between a BeginScene and EndScene pair,
3693 * except depth blits, which seem to work
3695 if(iface == myDevice->stencilBufferTarget || (SrcSurface && SrcSurface == myDevice->stencilBufferTarget)) {
3696 if(myDevice->inScene && !(Flags & WINEDDBLT_DEPTHFILL)) {
3697 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3698 return WINED3DERR_INVALIDCALL;
3699 } else if(IWineD3DSurfaceImpl_BltZ(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx) == WINED3D_OK) {
3700 TRACE("Z Blit override handled the blit\n");
3701 return WINED3D_OK;
3705 /* Special cases for RenderTargets */
3706 if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3707 ( Src && (Src->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3708 if(IWineD3DSurfaceImpl_BltOverride(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter) == WINED3D_OK) return WINED3D_OK;
3711 /* For the rest call the X11 surface implementation.
3712 * For RenderTargets this should be implemented OpenGL accelerated in BltOverride,
3713 * other Blts are rather rare
3715 return IWineD3DBaseSurfaceImpl_Blt(iface, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter);
3718 HRESULT WINAPI IWineD3DSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty, IWineD3DSurface *Source, RECT *rsrc, DWORD trans) {
3719 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3720 IWineD3DSurfaceImpl *srcImpl = (IWineD3DSurfaceImpl *) Source;
3721 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3722 TRACE("(%p)->(%d, %d, %p, %p, %08x\n", iface, dstx, dsty, Source, rsrc, trans);
3724 if ( (This->Flags & SFLAG_LOCKED) || ((srcImpl != NULL) && (srcImpl->Flags & SFLAG_LOCKED)))
3726 WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3727 return WINEDDERR_SURFACEBUSY;
3730 if(myDevice->inScene &&
3731 (iface == myDevice->stencilBufferTarget ||
3732 (Source && Source == myDevice->stencilBufferTarget))) {
3733 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3734 return WINED3DERR_INVALIDCALL;
3737 /* Special cases for RenderTargets */
3738 if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3739 ( srcImpl && (srcImpl->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3741 RECT SrcRect, DstRect;
3742 DWORD Flags=0;
3744 if(rsrc) {
3745 SrcRect.left = rsrc->left;
3746 SrcRect.top= rsrc->top;
3747 SrcRect.bottom = rsrc->bottom;
3748 SrcRect.right = rsrc->right;
3749 } else {
3750 SrcRect.left = 0;
3751 SrcRect.top = 0;
3752 SrcRect.right = srcImpl->currentDesc.Width;
3753 SrcRect.bottom = srcImpl->currentDesc.Height;
3756 DstRect.left = dstx;
3757 DstRect.top=dsty;
3758 DstRect.right = dstx + SrcRect.right - SrcRect.left;
3759 DstRect.bottom = dsty + SrcRect.bottom - SrcRect.top;
3761 /* Convert BltFast flags into Btl ones because it is called from SurfaceImpl_Blt as well */
3762 if(trans & WINEDDBLTFAST_SRCCOLORKEY)
3763 Flags |= WINEDDBLT_KEYSRC;
3764 if(trans & WINEDDBLTFAST_DESTCOLORKEY)
3765 Flags |= WINEDDBLT_KEYDEST;
3766 if(trans & WINEDDBLTFAST_WAIT)
3767 Flags |= WINEDDBLT_WAIT;
3768 if(trans & WINEDDBLTFAST_DONOTWAIT)
3769 Flags |= WINEDDBLT_DONOTWAIT;
3771 if(IWineD3DSurfaceImpl_BltOverride(This, &DstRect, Source, &SrcRect, Flags, NULL, WINED3DTEXF_POINT) == WINED3D_OK) return WINED3D_OK;
3775 return IWineD3DBaseSurfaceImpl_BltFast(iface, dstx, dsty, Source, rsrc, trans);
3778 HRESULT WINAPI IWineD3DSurfaceImpl_RealizePalette(IWineD3DSurface *iface) {
3779 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3780 RGBQUAD col[256];
3781 IWineD3DPaletteImpl *pal = This->palette;
3782 unsigned int n;
3783 TRACE("(%p)\n", This);
3785 if (!pal) return WINED3D_OK;
3787 if(This->resource.format == WINED3DFMT_P8 ||
3788 This->resource.format == WINED3DFMT_A8P8)
3790 int bpp;
3791 GLenum format, internal, type;
3792 CONVERT_TYPES convert;
3794 /* Check if we are using a RTL mode which uses texturing for uploads */
3795 BOOL use_texture = (wined3d_settings.rendertargetlock_mode == RTL_READTEX || wined3d_settings.rendertargetlock_mode == RTL_TEXTEX);
3797 /* Check if we have hardware palette conversion if we have convert is set to NO_CONVERSION */
3798 d3dfmt_get_conv(This, TRUE, use_texture, &format, &internal, &type, &convert, &bpp, This->srgb);
3800 if((This->resource.usage & WINED3DUSAGE_RENDERTARGET) && (convert == NO_CONVERSION))
3802 /* Make sure the texture is up to date. This call doesn't do anything if the texture is already up to date. */
3803 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL);
3805 /* We want to force a palette refresh, so mark the drawable as not being up to date */
3806 IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, FALSE);
3808 /* Re-upload the palette */
3809 d3dfmt_p8_upload_palette(iface, convert);
3811 /* Without this some palette updates are missed. This at least happens on Nvidia drivers but
3812 * it works fine using Mesa. */
3813 glFlush();
3814 } else {
3815 if(!(This->Flags & SFLAG_INSYSMEM)) {
3816 TRACE("Palette changed with surface that does not have an up to date system memory copy\n");
3817 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
3819 TRACE("Dirtifying surface\n");
3820 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
3824 if(This->Flags & SFLAG_DIBSECTION) {
3825 TRACE("(%p): Updating the hdc's palette\n", This);
3826 for (n=0; n<256; n++) {
3827 col[n].rgbRed = pal->palents[n].peRed;
3828 col[n].rgbGreen = pal->palents[n].peGreen;
3829 col[n].rgbBlue = pal->palents[n].peBlue;
3830 col[n].rgbReserved = 0;
3832 SetDIBColorTable(This->hDC, 0, 256, col);
3835 /* Propagate the changes to the drawable when we have a palette. */
3836 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3837 IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, NULL);
3839 return WINED3D_OK;
3842 static HRESULT WINAPI IWineD3DSurfaceImpl_PrivateSetup(IWineD3DSurface *iface) {
3843 /** Check against the maximum texture sizes supported by the video card **/
3844 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3845 unsigned int pow2Width, pow2Height;
3846 const GlPixelFormatDesc *glDesc;
3848 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
3849 /* Setup some glformat defaults */
3850 This->glDescription.glFormat = glDesc->glFormat;
3851 This->glDescription.glFormatInternal = glDesc->glInternal;
3852 This->glDescription.glType = glDesc->glType;
3854 This->glDescription.textureName = 0;
3855 This->glDescription.target = GL_TEXTURE_2D;
3857 /* Non-power2 support */
3858 if (GL_SUPPORT(ARB_TEXTURE_NON_POWER_OF_TWO) || GL_SUPPORT(WINE_NORMALIZED_TEXRECT)) {
3859 pow2Width = This->currentDesc.Width;
3860 pow2Height = This->currentDesc.Height;
3861 } else {
3862 /* Find the nearest pow2 match */
3863 pow2Width = pow2Height = 1;
3864 while (pow2Width < This->currentDesc.Width) pow2Width <<= 1;
3865 while (pow2Height < This->currentDesc.Height) pow2Height <<= 1;
3867 This->pow2Width = pow2Width;
3868 This->pow2Height = pow2Height;
3870 if (pow2Width > This->currentDesc.Width || pow2Height > This->currentDesc.Height) {
3871 WINED3DFORMAT Format = This->resource.format;
3872 /** TODO: add support for non power two compressed textures **/
3873 if (Format == WINED3DFMT_DXT1 || Format == WINED3DFMT_DXT2 || Format == WINED3DFMT_DXT3
3874 || Format == WINED3DFMT_DXT4 || Format == WINED3DFMT_DXT5
3875 || This->resource.format == WINED3DFMT_ATI2N) {
3876 FIXME("(%p) Compressed non-power-two textures are not supported w(%d) h(%d)\n",
3877 This, This->currentDesc.Width, This->currentDesc.Height);
3878 return WINED3DERR_NOTAVAILABLE;
3882 if(pow2Width != This->currentDesc.Width ||
3883 pow2Height != This->currentDesc.Height) {
3884 This->Flags |= SFLAG_NONPOW2;
3887 TRACE("%p\n", This);
3888 if ((This->pow2Width > GL_LIMITS(texture_size) || This->pow2Height > GL_LIMITS(texture_size)) && !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL))) {
3889 /* one of three options
3890 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)
3891 2: Set the texture to the maximum size (bad idea)
3892 3: WARN and return WINED3DERR_NOTAVAILABLE;
3893 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.
3895 WARN("(%p) Creating an oversized surface\n", This);
3896 This->Flags |= SFLAG_OVERSIZE;
3898 /* This will be initialized on the first blt */
3899 This->glRect.left = 0;
3900 This->glRect.top = 0;
3901 This->glRect.right = 0;
3902 This->glRect.bottom = 0;
3903 } else {
3904 /* Check this after the oversize check - do not make an oversized surface a texture_rectangle one.
3905 Second also don't use ARB_TEXTURE_RECTANGLE in case the surface format is P8 and EXT_PALETTED_TEXTURE
3906 is used in combination with texture uploads (RTL_READTEX/RTL_TEXTEX). The reason is that EXT_PALETTED_TEXTURE
3907 doesn't work in combination with ARB_TEXTURE_RECTANGLE.
3909 if(This->Flags & SFLAG_NONPOW2 && GL_SUPPORT(ARB_TEXTURE_RECTANGLE) &&
3910 !((This->resource.format == WINED3DFMT_P8) && GL_SUPPORT(EXT_PALETTED_TEXTURE) && (wined3d_settings.rendertargetlock_mode == RTL_READTEX || wined3d_settings.rendertargetlock_mode == RTL_TEXTEX)))
3912 This->glDescription.target = GL_TEXTURE_RECTANGLE_ARB;
3913 This->pow2Width = This->currentDesc.Width;
3914 This->pow2Height = This->currentDesc.Height;
3915 This->Flags &= ~(SFLAG_NONPOW2 | SFLAG_NORMCOORD);
3918 /* No oversize, gl rect is the full texture size */
3919 This->Flags &= ~SFLAG_OVERSIZE;
3920 This->glRect.left = 0;
3921 This->glRect.top = 0;
3922 This->glRect.right = This->pow2Width;
3923 This->glRect.bottom = This->pow2Height;
3926 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
3927 switch(wined3d_settings.offscreen_rendering_mode) {
3928 case ORM_FBO: This->get_drawable_size = get_drawable_size_fbo; break;
3929 case ORM_PBUFFER: This->get_drawable_size = get_drawable_size_pbuffer; break;
3930 case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
3934 This->Flags |= SFLAG_INSYSMEM;
3936 return WINED3D_OK;
3939 void surface_modify_ds_location(IWineD3DSurface *iface, DWORD location) {
3940 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3942 TRACE("(%p) New location %#x\n", This, location);
3944 if (location & ~SFLAG_DS_LOCATIONS) {
3945 FIXME("(%p) Invalid location (%#x) specified\n", This, location);
3948 This->Flags &= ~SFLAG_DS_LOCATIONS;
3949 This->Flags |= location;
3952 void surface_load_ds_location(IWineD3DSurface *iface, DWORD location) {
3953 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3954 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
3956 TRACE("(%p) New location %#x\n", This, location);
3958 /* TODO: Make this work for modes other than FBO */
3959 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return;
3961 if (This->Flags & location) {
3962 TRACE("(%p) Location (%#x) is already up to date\n", This, location);
3963 return;
3966 if (This->current_renderbuffer) {
3967 FIXME("(%p) Not supported with fixed up depth stencil\n", This);
3968 return;
3971 if (location == SFLAG_DS_OFFSCREEN) {
3972 if (This->Flags & SFLAG_DS_ONSCREEN) {
3973 GLint old_binding = 0;
3975 TRACE("(%p) Copying onscreen depth buffer to depth texture\n", This);
3977 ENTER_GL();
3979 if (!device->depth_blt_texture) {
3980 glGenTextures(1, &device->depth_blt_texture);
3983 /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
3984 * directly on the FBO texture. That's because we need to flip. */
3985 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
3986 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
3987 glBindTexture(GL_TEXTURE_2D, device->depth_blt_texture);
3988 glCopyTexImage2D(This->glDescription.target,
3989 This->glDescription.level,
3990 This->glDescription.glFormatInternal,
3993 This->currentDesc.Width,
3994 This->currentDesc.Height,
3996 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
3997 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
3998 glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
3999 glBindTexture(GL_TEXTURE_2D, old_binding);
4001 /* Setup the destination */
4002 if (!device->depth_blt_rb) {
4003 GL_EXTCALL(glGenRenderbuffersEXT(1, &device->depth_blt_rb));
4004 checkGLcall("glGenRenderbuffersEXT");
4006 if (device->depth_blt_rb_w != This->currentDesc.Width
4007 || device->depth_blt_rb_h != This->currentDesc.Height) {
4008 GL_EXTCALL(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, device->depth_blt_rb));
4009 checkGLcall("glBindRenderbufferEXT");
4010 GL_EXTCALL(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA8, This->currentDesc.Width, This->currentDesc.Height));
4011 checkGLcall("glRenderbufferStorageEXT");
4012 device->depth_blt_rb_w = This->currentDesc.Width;
4013 device->depth_blt_rb_h = This->currentDesc.Height;
4016 bind_fbo((IWineD3DDevice *)device, GL_FRAMEBUFFER_EXT, &device->activeContext->dst_fbo);
4017 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, device->depth_blt_rb));
4018 checkGLcall("glFramebufferRenderbufferEXT");
4019 attach_depth_stencil_fbo(device, GL_FRAMEBUFFER_EXT, iface, FALSE);
4021 /* Do the actual blit */
4022 depth_blt((IWineD3DDevice *)device, device->depth_blt_texture);
4023 checkGLcall("depth_blt");
4025 if (device->render_offscreen) {
4026 bind_fbo((IWineD3DDevice *)device, GL_FRAMEBUFFER_EXT, &device->activeContext->fbo);
4027 } else {
4028 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
4029 checkGLcall("glBindFramebuffer()");
4032 LEAVE_GL();
4033 } else {
4034 FIXME("No up to date depth stencil location\n");
4036 } else if (location == SFLAG_DS_ONSCREEN) {
4037 if (This->Flags & SFLAG_DS_OFFSCREEN) {
4038 TRACE("(%p) Copying depth texture to onscreen depth buffer\n", This);
4040 ENTER_GL();
4042 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
4043 checkGLcall("glBindFramebuffer()");
4044 depth_blt((IWineD3DDevice *)device, This->glDescription.textureName);
4045 checkGLcall("depth_blt");
4047 if (device->render_offscreen) {
4048 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, device->activeContext->fbo));
4049 checkGLcall("glBindFramebuffer()");
4052 LEAVE_GL();
4053 } else {
4054 FIXME("No up to date depth stencil location\n");
4056 } else {
4057 ERR("(%p) Invalid location (%#x) specified\n", This, location);
4060 This->Flags |= location;
4063 static void WINAPI IWineD3DSurfaceImpl_ModifyLocation(IWineD3DSurface *iface, DWORD flag, BOOL persistent) {
4064 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4065 IWineD3DBaseTexture *texture;
4066 IWineD3DSurfaceImpl *overlay;
4068 TRACE("(%p)->(%s, %s)\n", iface,
4069 flag == SFLAG_INSYSMEM ? "SFLAG_INSYSMEM" : flag == SFLAG_INDRAWABLE ? "SFLAG_INDRAWABLE" : "SFLAG_INTEXTURE",
4070 persistent ? "TRUE" : "FALSE");
4072 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
4073 IWineD3DSwapChain *swapchain = NULL;
4075 if (SUCCEEDED(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
4076 TRACE("Surface %p is an onscreen surface\n", iface);
4078 IWineD3DSwapChain_Release(swapchain);
4079 } else {
4080 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4081 if (flag & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE)) flag |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4085 if(persistent) {
4086 if((This->Flags & SFLAG_INTEXTURE) && !(flag & SFLAG_INTEXTURE)) {
4087 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
4088 TRACE("Passing to container\n");
4089 IWineD3DBaseTexture_SetDirty(texture, TRUE);
4090 IWineD3DBaseTexture_Release(texture);
4093 This->Flags &= ~SFLAG_LOCATIONS;
4094 This->Flags |= flag;
4096 /* Redraw emulated overlays, if any */
4097 if(flag & SFLAG_INDRAWABLE && !list_empty(&This->overlays)) {
4098 LIST_FOR_EACH_ENTRY(overlay, &This->overlays, IWineD3DSurfaceImpl, overlay_entry) {
4099 IWineD3DSurface_DrawOverlay((IWineD3DSurface *) overlay);
4102 } else {
4103 if((This->Flags & SFLAG_INTEXTURE) && (flag & SFLAG_INTEXTURE)) {
4104 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
4105 TRACE("Passing to container\n");
4106 IWineD3DBaseTexture_SetDirty(texture, TRUE);
4107 IWineD3DBaseTexture_Release(texture);
4110 This->Flags &= ~flag;
4114 struct coords {
4115 GLfloat x, y, z;
4118 static inline void surface_blt_to_drawable(IWineD3DSurfaceImpl *This, const RECT *rect_in) {
4119 struct coords coords[4];
4120 RECT rect;
4121 IWineD3DSwapChain *swapchain = NULL;
4122 IWineD3DBaseTexture *texture = NULL;
4123 HRESULT hr;
4124 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
4126 if(rect_in) {
4127 rect = *rect_in;
4128 } else {
4129 rect.left = 0;
4130 rect.top = 0;
4131 rect.right = This->currentDesc.Width;
4132 rect.bottom = This->currentDesc.Height;
4135 ActivateContext(device, (IWineD3DSurface*)This, CTXUSAGE_BLIT);
4136 ENTER_GL();
4138 if(This->glDescription.target == GL_TEXTURE_RECTANGLE_ARB) {
4139 glEnable(GL_TEXTURE_RECTANGLE_ARB);
4140 checkGLcall("glEnable(GL_TEXTURE_RECTANGLE_ARB)");
4141 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, This->glDescription.textureName);
4142 checkGLcall("GL_TEXTURE_RECTANGLE_ARB, This->glDescription.textureName)");
4143 glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4144 checkGLcall("glTexParameteri");
4145 glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4146 checkGLcall("glTexParameteri");
4148 coords[0].x = rect.left;
4149 coords[0].z = 0;
4151 coords[1].x = rect.left;
4152 coords[1].z = 0;
4154 coords[2].x = rect.right;
4155 coords[2].z = 0;
4157 coords[3].x = rect.right;
4158 coords[3].z = 0;
4160 coords[0].y = rect.top;
4161 coords[1].y = rect.bottom;
4162 coords[2].y = rect.bottom;
4163 coords[3].y = rect.top;
4164 } else if(This->glDescription.target == GL_TEXTURE_2D) {
4165 glEnable(GL_TEXTURE_2D);
4166 checkGLcall("glEnable(GL_TEXTURE_2D)");
4167 glBindTexture(GL_TEXTURE_2D, This->glDescription.textureName);
4168 checkGLcall("GL_TEXTURE_2D, This->glDescription.textureName)");
4169 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4170 checkGLcall("glTexParameteri");
4171 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4172 checkGLcall("glTexParameteri");
4174 coords[0].x = (float)rect.left / This->pow2Width;
4175 coords[0].z = 0;
4177 coords[1].x = (float)rect.left / This->pow2Width;
4178 coords[1].z = 0;
4180 coords[2].x = (float)rect.right / This->pow2Width;
4181 coords[2].z = 0;
4183 coords[3].x = (float)rect.right / This->pow2Width;
4184 coords[3].z = 0;
4186 coords[0].y = (float)rect.top / This->pow2Height;
4187 coords[1].y = (float)rect.bottom / This->pow2Height;
4188 coords[2].y = (float)rect.bottom / This->pow2Height;
4189 coords[3].y = (float)rect.top / This->pow2Height;
4190 } else {
4191 /* Must be a cube map */
4192 glEnable(GL_TEXTURE_CUBE_MAP_ARB);
4193 checkGLcall("glEnable(GL_TEXTURE_CUBE_MAP_ARB)");
4194 glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, This->glDescription.textureName);
4195 checkGLcall("GL_TEXTURE_CUBE_MAP_ARB, This->glDescription.textureName)");
4196 glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4197 checkGLcall("glTexParameteri");
4198 glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4199 checkGLcall("glTexParameteri");
4201 switch(This->glDescription.target) {
4202 case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
4203 coords[0].x = 1; coords[0].y = -1; coords[0].z = 1;
4204 coords[1].x = 1; coords[1].y = 1; coords[1].z = 1;
4205 coords[2].x = 1; coords[2].y = 1; coords[2].z = -1;
4206 coords[3].x = 1; coords[3].y = -1; coords[3].z = -1;
4207 break;
4209 case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
4210 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
4211 coords[1].x = -1; coords[1].y = 1; coords[1].z = 1;
4212 coords[2].x = -1; coords[2].y = 1; coords[2].z = -1;
4213 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
4214 break;
4216 case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
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_Y:
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_Z:
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_Z:
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 default:
4245 ERR("Unexpected texture target\n");
4246 LEAVE_GL();
4247 return;
4251 glBegin(GL_QUADS);
4252 glTexCoord3fv(&coords[0].x);
4253 glVertex2i(rect.left, device->render_offscreen ? rect.bottom : rect.top);
4255 glTexCoord3fv(&coords[1].x);
4256 glVertex2i(rect.left, device->render_offscreen ? rect.top : rect.bottom);
4258 glTexCoord3fv(&coords[2].x);
4259 glVertex2i(rect.right, device->render_offscreen ? rect.top : rect.bottom);
4261 glTexCoord3fv(&coords[3].x);
4262 glVertex2i(rect.right, device->render_offscreen ? rect.bottom : rect.top);
4263 glEnd();
4264 checkGLcall("glEnd");
4266 if(This->glDescription.target != GL_TEXTURE_2D) {
4267 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
4268 checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
4269 } else {
4270 glDisable(GL_TEXTURE_2D);
4271 checkGLcall("glDisable(GL_TEXTURE_2D)");
4273 LEAVE_GL();
4275 hr = IWineD3DSurface_GetContainer((IWineD3DSurface*)This, &IID_IWineD3DSwapChain, (void **) &swapchain);
4276 if(hr == WINED3D_OK && swapchain) {
4277 /* Make sure to flush the buffers. This is needed in apps like Red Alert II and Tiberian SUN that use multiple WGL contexts. */
4278 if(((IWineD3DSwapChainImpl*)swapchain)->frontBuffer == (IWineD3DSurface*)This ||
4279 ((IWineD3DSwapChainImpl*)swapchain)->num_contexts >= 2)
4280 glFlush();
4282 IWineD3DSwapChain_Release(swapchain);
4283 } else {
4284 /* We changed the filtering settings on the texture. Inform the container about this to get the filters
4285 * reset properly next draw
4287 hr = IWineD3DSurface_GetContainer((IWineD3DSurface*)This, &IID_IWineD3DBaseTexture, (void **) &texture);
4288 if(hr == WINED3D_OK && texture) {
4289 ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
4290 ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
4291 ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
4292 IWineD3DBaseTexture_Release(texture);
4297 /*****************************************************************************
4298 * IWineD3DSurface::LoadLocation
4300 * Copies the current surface data from wherever it is to the requested
4301 * location. The location is one of the surface flags, SFLAG_INSYSMEM,
4302 * SFLAG_INTEXTURE and SFLAG_INDRAWABLE. When the surface is current in
4303 * multiple locations, the gl texture is preferred over the drawable, which is
4304 * preferred over system memory. The PBO counts as system memory. If rect is
4305 * not NULL, only the specified rectangle is copied (only supported for
4306 * sysmem<->drawable copies at the moment). If rect is NULL, the destination
4307 * location is marked up to date after the copy.
4309 * Parameters:
4310 * flag: Surface location flag to be updated
4311 * rect: rectangle to be copied
4313 * Returns:
4314 * WINED3D_OK on success
4315 * WINED3DERR_DEVICELOST on an internal error
4317 *****************************************************************************/
4318 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadLocation(IWineD3DSurface *iface, DWORD flag, const RECT *rect) {
4319 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4320 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
4321 IWineD3DSwapChain *swapchain = NULL;
4322 GLenum format, internal, type;
4323 CONVERT_TYPES convert;
4324 int bpp;
4325 int width, pitch, outpitch;
4326 BYTE *mem;
4328 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
4329 if (SUCCEEDED(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
4330 TRACE("Surface %p is an onscreen surface\n", iface);
4332 IWineD3DSwapChain_Release(swapchain);
4333 } else {
4334 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets.
4335 * Prefer SFLAG_INTEXTURE. */
4336 if (flag == SFLAG_INDRAWABLE) flag = SFLAG_INTEXTURE;
4340 TRACE("(%p)->(%s, %p)\n", iface,
4341 flag == SFLAG_INSYSMEM ? "SFLAG_INSYSMEM" : flag == SFLAG_INDRAWABLE ? "SFLAG_INDRAWABLE" : "SFLAG_INTEXTURE",
4342 rect);
4343 if(rect) {
4344 TRACE("Rectangle: (%d,%d)-(%d,%d)\n", rect->left, rect->top, rect->right, rect->bottom);
4347 if(This->Flags & flag) {
4348 TRACE("Location already up to date\n");
4349 return WINED3D_OK;
4352 if(!(This->Flags & SFLAG_LOCATIONS)) {
4353 ERR("Surface does not have any up to date location\n");
4354 This->Flags |= SFLAG_LOST;
4355 return WINED3DERR_DEVICELOST;
4358 if(flag == SFLAG_INSYSMEM) {
4359 surface_prepare_system_memory(This);
4361 /* Download the surface to system memory */
4362 if(This->Flags & SFLAG_INTEXTURE) {
4363 if(!device->isInDraw) ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
4364 surface_bind_and_dirtify(This);
4366 surface_download_data(This);
4367 } else {
4368 read_from_framebuffer(This, rect,
4369 This->resource.allocatedMemory,
4370 IWineD3DSurface_GetPitch(iface));
4372 } else if(flag == SFLAG_INDRAWABLE) {
4373 if(This->Flags & SFLAG_INTEXTURE) {
4374 surface_blt_to_drawable(This, rect);
4375 } else {
4376 d3dfmt_get_conv(This, TRUE /* We need color keying */, FALSE /* We won't use textures */, &format, &internal, &type, &convert, &bpp, This->srgb);
4378 /* The width is in 'length' not in bytes */
4379 width = This->currentDesc.Width;
4380 pitch = IWineD3DSurface_GetPitch(iface);
4382 /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4383 * but it isn't set (yet) in all cases it is getting called. */
4384 if((convert != NO_CONVERSION) && (This->Flags & SFLAG_PBO)) {
4385 TRACE("Removing the pbo attached to surface %p\n", This);
4386 surface_remove_pbo(This);
4389 if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
4390 int height = This->currentDesc.Height;
4392 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4393 outpitch = width * bpp;
4394 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4396 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4397 if(!mem) {
4398 ERR("Out of memory %d, %d!\n", outpitch, height);
4399 return WINED3DERR_OUTOFVIDEOMEMORY;
4401 d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
4403 This->Flags |= SFLAG_CONVERTED;
4404 } else {
4405 This->Flags &= ~SFLAG_CONVERTED;
4406 mem = This->resource.allocatedMemory;
4409 flush_to_framebuffer_drawpixels(This, format, type, bpp, mem);
4411 /* Don't delete PBO memory */
4412 if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
4413 HeapFree(GetProcessHeap(), 0, mem);
4415 } else /* if(flag == SFLAG_INTEXTURE) */ {
4416 if (This->Flags & SFLAG_INDRAWABLE) {
4417 read_from_framebuffer_texture(This);
4418 } else { /* Upload from system memory */
4419 d3dfmt_get_conv(This, TRUE /* We need color keying */, TRUE /* We will use textures */, &format, &internal, &type, &convert, &bpp, This->srgb);
4421 if(!device->isInDraw) ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
4422 surface_bind_and_dirtify(This);
4423 ENTER_GL();
4425 /* The only place where LoadTexture() might get called when isInDraw=1
4426 * is ActivateContext where lastActiveRenderTarget is preloaded.
4428 if(iface == device->lastActiveRenderTarget && device->isInDraw)
4429 ERR("Reading back render target but SFLAG_INDRAWABLE not set\n");
4431 /* Otherwise: System memory copy must be most up to date */
4433 if(This->CKeyFlags & WINEDDSD_CKSRCBLT) {
4434 This->Flags |= SFLAG_GLCKEY;
4435 This->glCKey = This->SrcBltCKey;
4437 else This->Flags &= ~SFLAG_GLCKEY;
4439 /* The width is in 'length' not in bytes */
4440 width = This->currentDesc.Width;
4441 pitch = IWineD3DSurface_GetPitch(iface);
4443 /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4444 * but it isn't set (yet) in all cases it is getting called. */
4445 if((convert != NO_CONVERSION) && (This->Flags & SFLAG_PBO)) {
4446 TRACE("Removing the pbo attached to surface %p\n", This);
4447 surface_remove_pbo(This);
4450 if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
4451 int height = This->currentDesc.Height;
4453 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4454 outpitch = width * bpp;
4455 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4457 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4458 if(!mem) {
4459 ERR("Out of memory %d, %d!\n", outpitch, height);
4460 return WINED3DERR_OUTOFVIDEOMEMORY;
4462 d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
4464 This->Flags |= SFLAG_CONVERTED;
4465 } else if( (This->resource.format == WINED3DFMT_P8) && (GL_SUPPORT(EXT_PALETTED_TEXTURE) || GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) ) {
4466 d3dfmt_p8_upload_palette(iface, convert);
4467 This->Flags &= ~SFLAG_CONVERTED;
4468 mem = This->resource.allocatedMemory;
4469 } else {
4470 This->Flags &= ~SFLAG_CONVERTED;
4471 mem = This->resource.allocatedMemory;
4474 /* Make sure the correct pitch is used */
4475 glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
4477 if ((This->Flags & SFLAG_NONPOW2) && !(This->Flags & SFLAG_OVERSIZE)) {
4478 TRACE("non power of two support\n");
4479 if(!(This->Flags & SFLAG_ALLOCATED)) {
4480 surface_allocate_surface(This, internal, This->pow2Width, This->pow2Height, format, type);
4482 if (mem || (This->Flags & SFLAG_PBO)) {
4483 surface_upload_data(This, internal, This->currentDesc.Width, This->currentDesc.Height, format, type, mem);
4485 } else {
4486 /* When making the realloc conditional, keep in mind that GL_APPLE_client_storage may be in use, and This->resource.allocatedMemory
4487 * changed. So also keep track of memory changes. In this case the texture has to be reallocated
4489 if(!(This->Flags & SFLAG_ALLOCATED)) {
4490 surface_allocate_surface(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type);
4492 if (mem || (This->Flags & SFLAG_PBO)) {
4493 surface_upload_data(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type, mem);
4497 /* Restore the default pitch */
4498 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
4499 LEAVE_GL();
4501 /* Don't delete PBO memory */
4502 if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
4503 HeapFree(GetProcessHeap(), 0, mem);
4507 if(rect == NULL) {
4508 This->Flags |= flag;
4511 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && !swapchain
4512 && (This->Flags & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE))) {
4513 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4514 This->Flags |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4517 return WINED3D_OK;
4520 HRESULT WINAPI IWineD3DSurfaceImpl_SetContainer(IWineD3DSurface *iface, IWineD3DBase *container) {
4521 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4522 IWineD3DSwapChain *swapchain = NULL;
4524 /* Update the drawable size method */
4525 if(container) {
4526 IWineD3DBase_QueryInterface(container, &IID_IWineD3DSwapChain, (void **) &swapchain);
4528 if(swapchain) {
4529 This->get_drawable_size = get_drawable_size_swapchain;
4530 IWineD3DSwapChain_Release(swapchain);
4531 } else if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
4532 switch(wined3d_settings.offscreen_rendering_mode) {
4533 case ORM_FBO: This->get_drawable_size = get_drawable_size_fbo; break;
4534 case ORM_PBUFFER: This->get_drawable_size = get_drawable_size_pbuffer; break;
4535 case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
4539 return IWineD3DBaseSurfaceImpl_SetContainer(iface, container);
4542 static WINED3DSURFTYPE WINAPI IWineD3DSurfaceImpl_GetImplType(IWineD3DSurface *iface) {
4543 return SURFACE_OPENGL;
4546 static HRESULT WINAPI IWineD3DSurfaceImpl_DrawOverlay(IWineD3DSurface *iface) {
4547 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4548 HRESULT hr;
4550 /* If there's no destination surface there is nothing to do */
4551 if(!This->overlay_dest) return WINED3D_OK;
4553 /* Blt calls ModifyLocation on the dest surface, which in turn calls DrawOverlay to
4554 * update the overlay. Prevent an endless recursion
4556 if(This->overlay_dest->Flags & SFLAG_INOVERLAYDRAW) {
4557 return WINED3D_OK;
4559 This->overlay_dest->Flags |= SFLAG_INOVERLAYDRAW;
4560 hr = IWineD3DSurfaceImpl_Blt((IWineD3DSurface *) This->overlay_dest, &This->overlay_destrect,
4561 iface, &This->overlay_srcrect, WINEDDBLT_WAIT,
4562 NULL, WINED3DTEXF_LINEAR);
4563 This->overlay_dest->Flags &= ~SFLAG_INOVERLAYDRAW;
4565 return hr;
4568 const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl =
4570 /* IUnknown */
4571 IWineD3DBaseSurfaceImpl_QueryInterface,
4572 IWineD3DBaseSurfaceImpl_AddRef,
4573 IWineD3DSurfaceImpl_Release,
4574 /* IWineD3DResource */
4575 IWineD3DBaseSurfaceImpl_GetParent,
4576 IWineD3DBaseSurfaceImpl_GetDevice,
4577 IWineD3DBaseSurfaceImpl_SetPrivateData,
4578 IWineD3DBaseSurfaceImpl_GetPrivateData,
4579 IWineD3DBaseSurfaceImpl_FreePrivateData,
4580 IWineD3DBaseSurfaceImpl_SetPriority,
4581 IWineD3DBaseSurfaceImpl_GetPriority,
4582 IWineD3DSurfaceImpl_PreLoad,
4583 IWineD3DSurfaceImpl_UnLoad,
4584 IWineD3DBaseSurfaceImpl_GetType,
4585 /* IWineD3DSurface */
4586 IWineD3DBaseSurfaceImpl_GetContainer,
4587 IWineD3DBaseSurfaceImpl_GetDesc,
4588 IWineD3DSurfaceImpl_LockRect,
4589 IWineD3DSurfaceImpl_UnlockRect,
4590 IWineD3DSurfaceImpl_GetDC,
4591 IWineD3DSurfaceImpl_ReleaseDC,
4592 IWineD3DSurfaceImpl_Flip,
4593 IWineD3DSurfaceImpl_Blt,
4594 IWineD3DBaseSurfaceImpl_GetBltStatus,
4595 IWineD3DBaseSurfaceImpl_GetFlipStatus,
4596 IWineD3DBaseSurfaceImpl_IsLost,
4597 IWineD3DBaseSurfaceImpl_Restore,
4598 IWineD3DSurfaceImpl_BltFast,
4599 IWineD3DBaseSurfaceImpl_GetPalette,
4600 IWineD3DBaseSurfaceImpl_SetPalette,
4601 IWineD3DSurfaceImpl_RealizePalette,
4602 IWineD3DBaseSurfaceImpl_SetColorKey,
4603 IWineD3DBaseSurfaceImpl_GetPitch,
4604 IWineD3DSurfaceImpl_SetMem,
4605 IWineD3DBaseSurfaceImpl_SetOverlayPosition,
4606 IWineD3DBaseSurfaceImpl_GetOverlayPosition,
4607 IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder,
4608 IWineD3DBaseSurfaceImpl_UpdateOverlay,
4609 IWineD3DBaseSurfaceImpl_SetClipper,
4610 IWineD3DBaseSurfaceImpl_GetClipper,
4611 /* Internal use: */
4612 IWineD3DSurfaceImpl_AddDirtyRect,
4613 IWineD3DSurfaceImpl_LoadTexture,
4614 IWineD3DSurfaceImpl_BindTexture,
4615 IWineD3DSurfaceImpl_SaveSnapshot,
4616 IWineD3DSurfaceImpl_SetContainer,
4617 IWineD3DSurfaceImpl_SetGlTextureDesc,
4618 IWineD3DSurfaceImpl_GetGlDesc,
4619 IWineD3DSurfaceImpl_GetData,
4620 IWineD3DSurfaceImpl_SetFormat,
4621 IWineD3DSurfaceImpl_PrivateSetup,
4622 IWineD3DSurfaceImpl_ModifyLocation,
4623 IWineD3DSurfaceImpl_LoadLocation,
4624 IWineD3DSurfaceImpl_GetImplType,
4625 IWineD3DSurfaceImpl_DrawOverlay
4627 #undef GLINFO_LOCATION
4629 #define GLINFO_LOCATION device->adapter->gl_info
4630 static HRESULT ffp_blit_alloc(IWineD3DDevice *iface) { return WINED3D_OK; }
4631 static void ffp_blit_free(IWineD3DDevice *iface) { }
4633 static HRESULT ffp_blit_set(IWineD3DDevice *iface, WINED3DFORMAT fmt, GLenum textype, UINT width, UINT height) {
4634 glEnable(textype);
4635 checkGLcall("glEnable(textype)");
4636 return WINED3D_OK;
4639 static void ffp_blit_unset(IWineD3DDevice *iface) {
4640 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
4641 glDisable(GL_TEXTURE_2D);
4642 checkGLcall("glDisable(GL_TEXTURE_2D)");
4643 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
4644 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
4645 checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
4647 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
4648 glDisable(GL_TEXTURE_RECTANGLE_ARB);
4649 checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
4653 static BOOL ffp_blit_conv_supported(WINED3DFORMAT fmt) {
4654 TRACE("Checking blit format support for format %s: [FAILED]\n", debug_d3dformat(fmt));
4655 return FALSE;
4658 const struct blit_shader ffp_blit = {
4659 ffp_blit_alloc,
4660 ffp_blit_free,
4661 ffp_blit_set,
4662 ffp_blit_unset,
4663 ffp_blit_conv_supported