winex11: Use the gdi display when initializing the keyboard to avoid creating a secon...
[wine] / dlls / wined3d / surface_base.c
1 /*
2  * IWineD3DSurface Implementation of management(non-rendering) functions
3  *
4  * Copyright 1998 Lionel Ulmer
5  * Copyright 2000-2001 TransGaming Technologies Inc.
6  * Copyright 2002-2005 Jason Edmeades
7  * Copyright 2002-2003 Raphael Junqueira
8  * Copyright 2004 Christian Costa
9  * Copyright 2005 Oliver Stieber
10  * Copyright 2006-2007 Stefan Dösinger for CodeWeavers
11  * Copyright 2007 Henri Verbeet
12  * Copyright 2006-2007 Roderick Colenbrander
13  *
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.
18  *
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.
23  *
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
27  */
28
29 #include "config.h"
30 #include "wine/port.h"
31 #include "wined3d_private.h"
32
33 #include <assert.h>
34
35 WINE_DEFAULT_DEBUG_CHANNEL(d3d_surface);
36
37 /* Do NOT define GLINFO_LOCATION in this file. THIS CODE MUST NOT USE IT */
38
39 /* *******************************************
40    IWineD3DSurface IUnknown parts follow
41    ******************************************* */
42 HRESULT WINAPI IWineD3DBaseSurfaceImpl_QueryInterface(IWineD3DSurface *iface, REFIID riid, LPVOID *ppobj)
43 {
44     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
45     /* Warn ,but be nice about things */
46     TRACE("(%p)->(%s,%p)\n", This,debugstr_guid(riid),ppobj);
47
48     if (IsEqualGUID(riid, &IID_IUnknown)
49         || IsEqualGUID(riid, &IID_IWineD3DBase)
50         || IsEqualGUID(riid, &IID_IWineD3DResource)
51         || IsEqualGUID(riid, &IID_IWineD3DSurface)) {
52         IUnknown_AddRef((IUnknown*)iface);
53         *ppobj = This;
54         return S_OK;
55         }
56         *ppobj = NULL;
57         return E_NOINTERFACE;
58 }
59
60 ULONG WINAPI IWineD3DBaseSurfaceImpl_AddRef(IWineD3DSurface *iface) {
61     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
62     ULONG ref = InterlockedIncrement(&This->resource.ref);
63     TRACE("(%p) : AddRef increasing from %d\n", This,ref - 1);
64     return ref;
65 }
66
67 /* ****************************************************
68    IWineD3DSurface IWineD3DResource parts follow
69    **************************************************** */
70 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetDevice(IWineD3DSurface *iface, IWineD3DDevice** ppDevice) {
71     return IWineD3DResourceImpl_GetDevice((IWineD3DResource *)iface, ppDevice);
72 }
73
74 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetPrivateData(IWineD3DSurface *iface, REFGUID refguid, CONST void* pData, DWORD SizeOfData, DWORD Flags) {
75     return IWineD3DResourceImpl_SetPrivateData((IWineD3DResource *)iface, refguid, pData, SizeOfData, Flags);
76 }
77
78 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetPrivateData(IWineD3DSurface *iface, REFGUID refguid, void* pData, DWORD* pSizeOfData) {
79     return IWineD3DResourceImpl_GetPrivateData((IWineD3DResource *)iface, refguid, pData, pSizeOfData);
80 }
81
82 HRESULT WINAPI IWineD3DBaseSurfaceImpl_FreePrivateData(IWineD3DSurface *iface, REFGUID refguid) {
83     return IWineD3DResourceImpl_FreePrivateData((IWineD3DResource *)iface, refguid);
84 }
85
86 DWORD   WINAPI IWineD3DBaseSurfaceImpl_SetPriority(IWineD3DSurface *iface, DWORD PriorityNew) {
87     return IWineD3DResourceImpl_SetPriority((IWineD3DResource *)iface, PriorityNew);
88 }
89
90 DWORD   WINAPI IWineD3DBaseSurfaceImpl_GetPriority(IWineD3DSurface *iface) {
91     return IWineD3DResourceImpl_GetPriority((IWineD3DResource *)iface);
92 }
93
94 WINED3DRESOURCETYPE WINAPI IWineD3DBaseSurfaceImpl_GetType(IWineD3DSurface *iface) {
95     TRACE("(%p) : calling resourceimpl_GetType\n", iface);
96     return IWineD3DResourceImpl_GetType((IWineD3DResource *)iface);
97 }
98
99 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetParent(IWineD3DSurface *iface, IUnknown **pParent) {
100     TRACE("(%p) : calling resourceimpl_GetParent\n", iface);
101     return IWineD3DResourceImpl_GetParent((IWineD3DResource *)iface, pParent);
102 }
103
104 /* ******************************************************
105    IWineD3DSurface IWineD3DSurface parts follow
106    ****************************************************** */
107
108 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetContainer(IWineD3DSurface* iface, REFIID riid, void** ppContainer) {
109     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
110     IWineD3DBase *container = 0;
111
112     TRACE("(This %p, riid %s, ppContainer %p)\n", This, debugstr_guid(riid), ppContainer);
113
114     if (!ppContainer) {
115         ERR("Called without a valid ppContainer.\n");
116     }
117
118     /** From MSDN:
119      * If the surface is created using CreateImageSurface/CreateOffscreenPlainSurface, CreateRenderTarget,
120      * or CreateDepthStencilSurface, the surface is considered stand alone. In this case,
121      * GetContainer will return the Direct3D device used to create the surface.
122      */
123     if (This->container) {
124         container = This->container;
125     } else {
126         container = (IWineD3DBase *)This->resource.wineD3DDevice;
127     }
128
129     TRACE("Relaying to QueryInterface\n");
130     return IUnknown_QueryInterface(container, riid, ppContainer);
131 }
132
133 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetDesc(IWineD3DSurface *iface, WINED3DSURFACE_DESC *pDesc) {
134     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
135
136     TRACE("(%p) : copying into %p\n", This, pDesc);
137     if(pDesc->Format != NULL)             *(pDesc->Format) = This->resource.format;
138     if(pDesc->Type != NULL)               *(pDesc->Type)   = This->resource.resourceType;
139     if(pDesc->Usage != NULL)              *(pDesc->Usage)              = This->resource.usage;
140     if(pDesc->Pool != NULL)               *(pDesc->Pool)               = This->resource.pool;
141     if(pDesc->Size != NULL)               *(pDesc->Size)               = This->resource.size;   /* dx8 only */
142     if(pDesc->MultiSampleType != NULL)    *(pDesc->MultiSampleType)    = This->currentDesc.MultiSampleType;
143     if(pDesc->MultiSampleQuality != NULL) *(pDesc->MultiSampleQuality) = This->currentDesc.MultiSampleQuality;
144     if(pDesc->Width != NULL)              *(pDesc->Width)              = This->currentDesc.Width;
145     if(pDesc->Height != NULL)             *(pDesc->Height)             = This->currentDesc.Height;
146     return WINED3D_OK;
147 }
148
149 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetBltStatus(IWineD3DSurface *iface, DWORD Flags) {
150     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
151     TRACE("(%p)->(%x)\n", This, Flags);
152
153     switch (Flags)
154     {
155         case WINEDDGBS_CANBLT:
156         case WINEDDGBS_ISBLTDONE:
157             return WINED3D_OK;
158
159         default:
160             return WINED3DERR_INVALIDCALL;
161     }
162 }
163
164 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetFlipStatus(IWineD3DSurface *iface, DWORD Flags) {
165     /* XXX: DDERR_INVALIDSURFACETYPE */
166
167     TRACE("(%p)->(%08x)\n",iface,Flags);
168     switch (Flags) {
169         case WINEDDGFS_CANFLIP:
170         case WINEDDGFS_ISFLIPDONE:
171             return WINED3D_OK;
172
173         default:
174             return WINED3DERR_INVALIDCALL;
175     }
176 }
177
178 HRESULT WINAPI IWineD3DBaseSurfaceImpl_IsLost(IWineD3DSurface *iface) {
179     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
180     TRACE("(%p)\n", This);
181
182     /* D3D8 and 9 loose full devices, ddraw only surfaces */
183     return This->Flags & SFLAG_LOST ? WINED3DERR_DEVICELOST : WINED3D_OK;
184 }
185
186 HRESULT WINAPI IWineD3DBaseSurfaceImpl_Restore(IWineD3DSurface *iface) {
187     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
188     TRACE("(%p)\n", This);
189
190     /* So far we don't lose anything :) */
191     This->Flags &= ~SFLAG_LOST;
192     return WINED3D_OK;
193 }
194
195 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetPalette(IWineD3DSurface *iface, IWineD3DPalette *Pal) {
196     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
197     IWineD3DPaletteImpl *PalImpl = (IWineD3DPaletteImpl *) Pal;
198     TRACE("(%p)->(%p)\n", This, Pal);
199
200     if(This->palette != NULL)
201         if(This->resource.usage & WINED3DUSAGE_RENDERTARGET)
202             This->palette->Flags &= ~WINEDDPCAPS_PRIMARYSURFACE;
203
204     if(PalImpl != NULL) {
205         if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
206             /* Set the device's main palette if the palette
207             * wasn't a primary palette before
208             */
209             if(!(PalImpl->Flags & WINEDDPCAPS_PRIMARYSURFACE)) {
210                 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
211                 unsigned int i;
212
213                 for(i=0; i < 256; i++) {
214                     device->palettes[device->currentPalette][i] = PalImpl->palents[i];
215                 }
216             }
217
218             (PalImpl)->Flags |= WINEDDPCAPS_PRIMARYSURFACE;
219         }
220     }
221     This->palette = PalImpl;
222
223     return IWineD3DSurface_RealizePalette(iface);
224 }
225
226 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetColorKey(IWineD3DSurface *iface, DWORD Flags, WINEDDCOLORKEY *CKey) {
227     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
228     TRACE("(%p)->(%08x,%p)\n", This, Flags, CKey);
229
230     if ((Flags & WINEDDCKEY_COLORSPACE) != 0) {
231         FIXME(" colorkey value not supported (%08x) !\n", Flags);
232         return WINED3DERR_INVALIDCALL;
233     }
234
235     /* Dirtify the surface, but only if a key was changed */
236     if(CKey) {
237         switch (Flags & ~WINEDDCKEY_COLORSPACE) {
238             case WINEDDCKEY_DESTBLT:
239                 This->DestBltCKey = *CKey;
240                 This->CKeyFlags |= WINEDDSD_CKDESTBLT;
241                 break;
242
243             case WINEDDCKEY_DESTOVERLAY:
244                 This->DestOverlayCKey = *CKey;
245                 This->CKeyFlags |= WINEDDSD_CKDESTOVERLAY;
246                 break;
247
248             case WINEDDCKEY_SRCOVERLAY:
249                 This->SrcOverlayCKey = *CKey;
250                 This->CKeyFlags |= WINEDDSD_CKSRCOVERLAY;
251                 break;
252
253             case WINEDDCKEY_SRCBLT:
254                 This->SrcBltCKey = *CKey;
255                 This->CKeyFlags |= WINEDDSD_CKSRCBLT;
256                 break;
257         }
258     }
259     else {
260         switch (Flags & ~WINEDDCKEY_COLORSPACE) {
261             case WINEDDCKEY_DESTBLT:
262                 This->CKeyFlags &= ~WINEDDSD_CKDESTBLT;
263                 break;
264
265             case WINEDDCKEY_DESTOVERLAY:
266                 This->CKeyFlags &= ~WINEDDSD_CKDESTOVERLAY;
267                 break;
268
269             case WINEDDCKEY_SRCOVERLAY:
270                 This->CKeyFlags &= ~WINEDDSD_CKSRCOVERLAY;
271                 break;
272
273             case WINEDDCKEY_SRCBLT:
274                 This->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
275                 break;
276         }
277     }
278
279     return WINED3D_OK;
280 }
281
282 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetPalette(IWineD3DSurface *iface, IWineD3DPalette **Pal) {
283     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
284     TRACE("(%p)->(%p)\n", This, Pal);
285
286     *Pal = (IWineD3DPalette *) This->palette;
287     return WINED3D_OK;
288 }
289
290 HRESULT WINAPI IWineD3DBaseSurfaceImpl_RealizePalette(IWineD3DSurface *iface) {
291     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
292     RGBQUAD col[256];
293     IWineD3DPaletteImpl *pal = This->palette;
294     unsigned int n;
295     TRACE("(%p)\n", This);
296
297     if(This->resource.format == WINED3DFMT_P8 ||
298        This->resource.format == WINED3DFMT_A8P8)
299     {
300         if(!(This->Flags & SFLAG_INSYSMEM)) {
301             TRACE("Palette changed with surface that does not have an up to date system memory copy\n");
302             IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
303         }
304         TRACE("Dirtifying surface\n");
305         IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
306     }
307
308     if(This->Flags & SFLAG_DIBSECTION) {
309         TRACE("(%p): Updating the hdc's palette\n", This);
310         for (n=0; n<256; n++) {
311             if(pal) {
312                 col[n].rgbRed   = pal->palents[n].peRed;
313                 col[n].rgbGreen = pal->palents[n].peGreen;
314                 col[n].rgbBlue  = pal->palents[n].peBlue;
315             } else {
316                 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
317                 /* Use the default device palette */
318                 col[n].rgbRed   = device->palettes[device->currentPalette][n].peRed;
319                 col[n].rgbGreen = device->palettes[device->currentPalette][n].peGreen;
320                 col[n].rgbBlue  = device->palettes[device->currentPalette][n].peBlue;
321             }
322             col[n].rgbReserved = 0;
323         }
324         SetDIBColorTable(This->hDC, 0, 256, col);
325     }
326
327     return WINED3D_OK;
328 }
329
330 DWORD WINAPI IWineD3DBaseSurfaceImpl_GetPitch(IWineD3DSurface *iface) {
331     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
332     DWORD ret;
333     TRACE("(%p)\n", This);
334
335     /* DXTn formats don't have exact pitches as they are to the new row of blocks,
336     where each block is 4x4 pixels, 8 bytes (dxt1) and 16 bytes (dxt2/3/4/5)
337     ie pitch = (width/4) * bytes per block                                  */
338     if (This->resource.format == WINED3DFMT_DXT1) /* DXT1 is 8 bytes per block */
339         ret = ((This->currentDesc.Width + 3) >> 2) << 3;
340     else if (This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
341              This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5) /* DXT2/3/4/5 is 16 bytes per block */
342         ret = ((This->currentDesc.Width + 3) >> 2) << 4;
343     else {
344         unsigned char alignment = This->resource.wineD3DDevice->surface_alignment;
345         ret = This->bytesPerPixel * This->currentDesc.Width;  /* Bytes / row */
346         ret = (ret + alignment - 1) & ~(alignment - 1);
347     }
348     TRACE("(%p) Returning %d\n", This, ret);
349     return ret;
350 }
351
352 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetOverlayPosition(IWineD3DSurface *iface, LONG X, LONG Y) {
353     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
354
355     FIXME("(%p)->(%d,%d) Stub!\n", This, X, Y);
356
357     if(!(This->resource.usage & WINED3DUSAGE_OVERLAY))
358     {
359         TRACE("(%p): Not an overlay surface\n", This);
360         return WINEDDERR_NOTAOVERLAYSURFACE;
361     }
362
363     return WINED3D_OK;
364 }
365
366 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetOverlayPosition(IWineD3DSurface *iface, LONG *X, LONG *Y) {
367     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
368
369     FIXME("(%p)->(%p,%p) Stub!\n", This, X, Y);
370
371     if(!(This->resource.usage & WINED3DUSAGE_OVERLAY))
372     {
373         TRACE("(%p): Not an overlay surface\n", This);
374         return WINEDDERR_NOTAOVERLAYSURFACE;
375     }
376
377     return WINED3D_OK;
378 }
379
380 HRESULT WINAPI IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder(IWineD3DSurface *iface, DWORD Flags, IWineD3DSurface *Ref) {
381     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
382     IWineD3DSurfaceImpl *RefImpl = (IWineD3DSurfaceImpl *) Ref;
383
384     FIXME("(%p)->(%08x,%p) Stub!\n", This, Flags, RefImpl);
385
386     if(!(This->resource.usage & WINED3DUSAGE_OVERLAY))
387     {
388         TRACE("(%p): Not an overlay surface\n", This);
389         return WINEDDERR_NOTAOVERLAYSURFACE;
390     }
391
392     return WINED3D_OK;
393 }
394
395 HRESULT WINAPI IWineD3DBaseSurfaceImpl_UpdateOverlay(IWineD3DSurface *iface, RECT *SrcRect, IWineD3DSurface *DstSurface, RECT *DstRect, DWORD Flags, WINEDDOVERLAYFX *FX) {
396     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
397     IWineD3DSurfaceImpl *Dst = (IWineD3DSurfaceImpl *) DstSurface;
398     FIXME("(%p)->(%p, %p, %p, %08x, %p)\n", This, SrcRect, Dst, DstRect, Flags, FX);
399
400     if(!(This->resource.usage & WINED3DUSAGE_OVERLAY))
401     {
402         TRACE("(%p): Not an overlay surface\n", This);
403         return WINEDDERR_NOTAOVERLAYSURFACE;
404     }
405
406     return WINED3D_OK;
407 }
408
409 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetClipper(IWineD3DSurface *iface, IWineD3DClipper *clipper)
410 {
411     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
412     TRACE("(%p)->(%p)\n", This, clipper);
413
414     This->clipper = clipper;
415     return WINED3D_OK;
416 }
417
418 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetClipper(IWineD3DSurface *iface, IWineD3DClipper **clipper)
419 {
420     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
421     TRACE("(%p)->(%p)\n", This, clipper);
422
423     *clipper = This->clipper;
424     if(*clipper) {
425         IWineD3DClipper_AddRef(*clipper);
426     }
427     return WINED3D_OK;
428 }
429
430 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetContainer(IWineD3DSurface *iface, IWineD3DBase *container) {
431     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
432
433     TRACE("This %p, container %p\n", This, container);
434
435     /* We can't keep a reference to the container, since the container already keeps a reference to us. */
436
437     TRACE("Setting container to %p from %p\n", container, This->container);
438     This->container = container;
439
440     return WINED3D_OK;
441 }
442
443 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format) {
444     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
445     const StaticPixelFormatDesc *formatEntry = getFormatDescEntry(format, NULL, NULL);
446
447     if (This->resource.format != WINED3DFMT_UNKNOWN) {
448         FIXME("(%p) : The format of the surface must be WINED3DFORMAT_UNKNOWN\n", This);
449         return WINED3DERR_INVALIDCALL;
450     }
451
452     TRACE("(%p) : Setting texture format to (%d,%s)\n", This, format, debug_d3dformat(format));
453     if (format == WINED3DFMT_UNKNOWN) {
454         This->resource.size = 0;
455     } else if (format == WINED3DFMT_DXT1) {
456         /* DXT1 is half byte per pixel */
457         This->resource.size = ((max(This->pow2Width, 4) * formatEntry->bpp) * max(This->pow2Height, 4)) >> 1;
458
459     } else if (format == WINED3DFMT_DXT2 || format == WINED3DFMT_DXT3 ||
460                format == WINED3DFMT_DXT4 || format == WINED3DFMT_DXT5) {
461         This->resource.size = ((max(This->pow2Width, 4) * formatEntry->bpp) * max(This->pow2Height, 4));
462     } else {
463         unsigned char alignment = This->resource.wineD3DDevice->surface_alignment;
464         This->resource.size = ((This->pow2Width * formatEntry->bpp) + alignment - 1) & ~(alignment - 1);
465         This->resource.size *= This->pow2Height;
466     }
467
468     if (format != WINED3DFMT_UNKNOWN) {
469         This->bytesPerPixel = formatEntry->bpp;
470     } else {
471         This->bytesPerPixel = 0;
472     }
473
474     This->Flags |= (WINED3DFMT_D16_LOCKABLE == format) ? SFLAG_LOCKABLE : 0;
475
476     This->resource.format = format;
477
478     TRACE("(%p) : Size %d, bytesPerPixel %d\n", This, This->resource.size, This->bytesPerPixel);
479
480     return WINED3D_OK;
481 }
482
483 HRESULT IWineD3DBaseSurfaceImpl_CreateDIBSection(IWineD3DSurface *iface) {
484     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
485     int extraline = 0;
486     SYSTEM_INFO sysInfo;
487     BITMAPINFO* b_info;
488     HDC ddc;
489     DWORD *masks;
490     const StaticPixelFormatDesc *formatEntry = getFormatDescEntry(This->resource.format, NULL, NULL);
491     UINT usage;
492
493     switch (This->bytesPerPixel) {
494         case 2:
495         case 4:
496             /* Allocate extra space to store the RGB bit masks. */
497             b_info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 3 * sizeof(DWORD));
498             break;
499
500         case 3:
501             b_info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER));
502             break;
503
504         default:
505             /* Allocate extra space for a palette. */
506             b_info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
507                                sizeof(BITMAPINFOHEADER)
508                                + sizeof(RGBQUAD)
509                                * (1 << (This->bytesPerPixel * 8)));
510             break;
511     }
512
513     if (!b_info)
514         return E_OUTOFMEMORY;
515
516         /* Some apps access the surface in via DWORDs, and do not take the necessary care at the end of the
517     * surface. So we need at least extra 4 bytes at the end of the surface. Check against the page size,
518     * if the last page used for the surface has at least 4 spare bytes we're safe, otherwise
519     * add an extra line to the dib section
520         */
521     GetSystemInfo(&sysInfo);
522     if( ((This->resource.size + 3) % sysInfo.dwPageSize) < 4) {
523         extraline = 1;
524         TRACE("Adding an extra line to the dib section\n");
525     }
526
527     b_info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
528     /* TODO: Is there a nicer way to force a specific alignment? (8 byte for ddraw) */
529     b_info->bmiHeader.biWidth = IWineD3DSurface_GetPitch(iface) / This->bytesPerPixel;
530     b_info->bmiHeader.biHeight = -This->currentDesc.Height -extraline;
531     b_info->bmiHeader.biSizeImage = ( This->currentDesc.Height + extraline) * IWineD3DSurface_GetPitch(iface);
532     b_info->bmiHeader.biPlanes = 1;
533     b_info->bmiHeader.biBitCount = This->bytesPerPixel * 8;
534
535     b_info->bmiHeader.biXPelsPerMeter = 0;
536     b_info->bmiHeader.biYPelsPerMeter = 0;
537     b_info->bmiHeader.biClrUsed = 0;
538     b_info->bmiHeader.biClrImportant = 0;
539
540     /* Get the bit masks */
541     masks = (DWORD *) &(b_info->bmiColors);
542     switch (This->resource.format) {
543         case WINED3DFMT_R8G8B8:
544             usage = DIB_RGB_COLORS;
545             b_info->bmiHeader.biCompression = BI_RGB;
546             break;
547
548         case WINED3DFMT_X1R5G5B5:
549         case WINED3DFMT_A1R5G5B5:
550         case WINED3DFMT_A4R4G4B4:
551         case WINED3DFMT_X4R4G4B4:
552         case WINED3DFMT_R3G3B2:
553         case WINED3DFMT_A8R3G3B2:
554         case WINED3DFMT_A2B10G10R10:
555         case WINED3DFMT_A8B8G8R8:
556         case WINED3DFMT_X8B8G8R8:
557         case WINED3DFMT_A2R10G10B10:
558         case WINED3DFMT_R5G6B5:
559         case WINED3DFMT_A16B16G16R16:
560             usage = 0;
561             b_info->bmiHeader.biCompression = BI_BITFIELDS;
562             masks[0] = formatEntry->redMask;
563             masks[1] = formatEntry->greenMask;
564             masks[2] = formatEntry->blueMask;
565             break;
566
567         default:
568             /* Don't know palette */
569             b_info->bmiHeader.biCompression = BI_RGB;
570             usage = 0;
571             break;
572     }
573
574     ddc = GetDC(0);
575     if (ddc == 0) {
576         HeapFree(GetProcessHeap(), 0, b_info);
577         return HRESULT_FROM_WIN32(GetLastError());
578     }
579
580     TRACE("Creating a DIB section with size %dx%dx%d, size=%d\n", b_info->bmiHeader.biWidth, b_info->bmiHeader.biHeight, b_info->bmiHeader.biBitCount, b_info->bmiHeader.biSizeImage);
581     This->dib.DIBsection = CreateDIBSection(ddc, b_info, usage, &This->dib.bitmap_data, 0 /* Handle */, 0 /* Offset */);
582     ReleaseDC(0, ddc);
583
584     if (!This->dib.DIBsection) {
585         ERR("CreateDIBSection failed!\n");
586         HeapFree(GetProcessHeap(), 0, b_info);
587         return HRESULT_FROM_WIN32(GetLastError());
588     }
589
590     TRACE("DIBSection at : %p\n", This->dib.bitmap_data);
591     /* copy the existing surface to the dib section */
592     if(This->resource.allocatedMemory) {
593         memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, b_info->bmiHeader.biSizeImage);
594     } else {
595         /* This is to make LockRect read the gl Texture although memory is allocated */
596         This->Flags &= ~SFLAG_INSYSMEM;
597     }
598     This->dib.bitmap_size = b_info->bmiHeader.biSizeImage;
599
600     HeapFree(GetProcessHeap(), 0, b_info);
601
602     /* Now allocate a HDC */
603     This->hDC = CreateCompatibleDC(0);
604     This->dib.holdbitmap = SelectObject(This->hDC, This->dib.DIBsection);
605     TRACE("using wined3d palette %p\n", This->palette);
606     SelectPalette(This->hDC,
607                   This->palette ? This->palette->hpal : 0,
608                   FALSE);
609
610     This->Flags |= SFLAG_DIBSECTION;
611
612     HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
613     This->resource.heapMemory = NULL;
614
615     return WINED3D_OK;
616 }
617
618 /*****************************************************************************
619  * _Blt_ColorFill
620  *
621  * Helper function that fills a memory area with a specific color
622  *
623  * Params:
624  *  buf: memory address to start filling at
625  *  width, height: Dimensions of the area to fill
626  *  bpp: Bit depth of the surface
627  *  lPitch: pitch of the surface
628  *  color: Color to fill with
629  *
630  *****************************************************************************/
631 static HRESULT
632         _Blt_ColorFill(BYTE *buf,
633                        int width, int height,
634                        int bpp, LONG lPitch,
635                        DWORD color)
636 {
637     int x, y;
638     LPBYTE first;
639
640     /* Do first row */
641
642 #define COLORFILL_ROW(type) \
643     { \
644     type *d = (type *) buf; \
645     for (x = 0; x < width; x++) \
646     d[x] = (type) color; \
647     break; \
648 }
649     switch(bpp)
650     {
651         case 1: COLORFILL_ROW(BYTE)
652                 case 2: COLORFILL_ROW(WORD)
653         case 3:
654         {
655             BYTE *d = buf;
656             for (x = 0; x < width; x++,d+=3)
657             {
658                 d[0] = (color    ) & 0xFF;
659                 d[1] = (color>> 8) & 0xFF;
660                 d[2] = (color>>16) & 0xFF;
661             }
662             break;
663         }
664         case 4: COLORFILL_ROW(DWORD)
665         default:
666             FIXME("Color fill not implemented for bpp %d!\n", bpp*8);
667             return WINED3DERR_NOTAVAILABLE;
668     }
669
670 #undef COLORFILL_ROW
671
672     /* Now copy first row */
673     first = buf;
674     for (y = 1; y < height; y++)
675     {
676         buf += lPitch;
677         memcpy(buf, first, width * bpp);
678     }
679     return WINED3D_OK;
680 }
681
682 /*****************************************************************************
683  * IWineD3DSurface::Blt, SW emulation version
684  *
685  * Performs blits to a surface, eigher from a source of source-less blts
686  * This is the main functionality of DirectDraw
687  *
688  * Params:
689  *  DestRect: Destination rectangle to write to
690  *  SrcSurface: Source surface, can be NULL
691  *  SrcRect: Source rectangle
692  *****************************************************************************/
693 HRESULT WINAPI
694 IWineD3DBaseSurfaceImpl_Blt(IWineD3DSurface *iface,
695                             RECT *DestRect,
696                             IWineD3DSurface *SrcSurface,
697                             RECT *SrcRect,
698                             DWORD Flags,
699                             WINEDDBLTFX *DDBltFx,
700                             WINED3DTEXTUREFILTERTYPE Filter)
701 {
702     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
703     IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
704     RECT        xdst,xsrc;
705     HRESULT     ret = WINED3D_OK;
706     WINED3DLOCKED_RECT  dlock, slock;
707     WINED3DFORMAT       dfmt = WINED3DFMT_UNKNOWN, sfmt = WINED3DFMT_UNKNOWN;
708     int bpp, srcheight, srcwidth, dstheight, dstwidth, width;
709     int x, y;
710     const StaticPixelFormatDesc *sEntry, *dEntry;
711     LPBYTE dbuf, sbuf;
712     TRACE("(%p)->(%p,%p,%p,%x,%p)\n", This, DestRect, Src, SrcRect, Flags, DDBltFx);
713
714     if (TRACE_ON(d3d_surface))
715     {
716         if (DestRect) TRACE("\tdestrect :%dx%d-%dx%d\n",
717             DestRect->left, DestRect->top, DestRect->right, DestRect->bottom);
718         if (SrcRect) TRACE("\tsrcrect  :%dx%d-%dx%d\n",
719             SrcRect->left, SrcRect->top, SrcRect->right, SrcRect->bottom);
720 #if 0
721         TRACE("\tflags: ");
722                       DDRAW_dump_DDBLT(Flags);
723                       if (Flags & WINEDDBLT_DDFX)
724               {
725                       TRACE("\tblitfx: ");
726                       DDRAW_dump_DDBLTFX(DDBltFx->dwDDFX);
727     }
728 #endif
729     }
730
731     if ( (This->Flags & SFLAG_LOCKED) || ((Src != NULL) && (Src->Flags & SFLAG_LOCKED)))
732     {
733         WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
734         return WINEDDERR_SURFACEBUSY;
735     }
736
737     if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
738         /* Can happen when d3d9 apps do a StretchRect call which isn't handled in gl */
739         FIXME("Filters not supported in software blit\n");
740     }
741
742     if (Src == This)
743     {
744         IWineD3DSurface_LockRect(iface, &dlock, NULL, 0);
745         dfmt = This->resource.format;
746         slock = dlock;
747         sfmt = dfmt;
748         sEntry = getFormatDescEntry(sfmt, NULL, NULL);
749         dEntry = sEntry;
750     }
751     else
752     {
753         if (Src)
754         {
755             IWineD3DSurface_LockRect(SrcSurface, &slock, NULL, WINED3DLOCK_READONLY);
756             sfmt = Src->resource.format;
757         }
758         sEntry = getFormatDescEntry(sfmt, NULL, NULL);
759         dfmt = This->resource.format;
760         dEntry = getFormatDescEntry(dfmt, NULL, NULL);
761         IWineD3DSurface_LockRect(iface, &dlock,NULL,0);
762     }
763
764     if (!DDBltFx || !(DDBltFx->dwDDFX)) Flags &= ~WINEDDBLT_DDFX;
765
766     if (sEntry->isFourcc && dEntry->isFourcc)
767     {
768         if (sfmt != dfmt)
769         {
770             FIXME("FOURCC->FOURCC copy only supported for the same type of surface\n");
771             ret = WINED3DERR_WRONGTEXTUREFORMAT;
772             goto release;
773         }
774         memcpy(dlock.pBits, slock.pBits, This->resource.size);
775         goto release;
776     }
777
778     if (sEntry->isFourcc && !dEntry->isFourcc)
779     {
780         FIXME("DXTC decompression not supported right now\n");
781         goto release;
782     }
783
784     if (DestRect)
785     {
786         memcpy(&xdst,DestRect,sizeof(xdst));
787     }
788     else
789     {
790         xdst.top    = 0;
791         xdst.bottom = This->currentDesc.Height;
792         xdst.left   = 0;
793         xdst.right  = This->currentDesc.Width;
794     }
795
796     if (SrcRect)
797     {
798         memcpy(&xsrc,SrcRect,sizeof(xsrc));
799     }
800     else
801     {
802         if (Src)
803         {
804             xsrc.top    = 0;
805             xsrc.bottom = Src->currentDesc.Height;
806             xsrc.left   = 0;
807             xsrc.right  = Src->currentDesc.Width;
808         }
809         else
810         {
811             memset(&xsrc,0,sizeof(xsrc));
812         }
813     }
814
815     /* First check for the validity of source / destination rectangles. This was
816      * verified using a test application + by MSDN.
817      */
818     if ((Src != NULL) &&
819          ((xsrc.bottom > Src->currentDesc.Height) || (xsrc.bottom < 0) ||
820          (xsrc.top     > Src->currentDesc.Height) || (xsrc.top    < 0) ||
821          (xsrc.left    > Src->currentDesc.Width)  || (xsrc.left   < 0) ||
822          (xsrc.right   > Src->currentDesc.Width)  || (xsrc.right  < 0) ||
823          (xsrc.right   < xsrc.left)               || (xsrc.bottom < xsrc.top)))
824     {
825         WARN("Application gave us bad source rectangle for Blt.\n");
826         ret = WINEDDERR_INVALIDRECT;
827         goto release;
828     }
829     /* For the Destination rect, it can be out of bounds on the condition that a clipper
830      * is set for the given surface.
831      */
832     if ((/*This->clipper == NULL*/ TRUE) &&
833          ((xdst.bottom  > This->currentDesc.Height) || (xdst.bottom < 0) ||
834          (xdst.top      > This->currentDesc.Height) || (xdst.top    < 0) ||
835          (xdst.left     > This->currentDesc.Width)  || (xdst.left   < 0) ||
836          (xdst.right    > This->currentDesc.Width)  || (xdst.right  < 0) ||
837          (xdst.right    < xdst.left)                || (xdst.bottom < xdst.top)))
838     {
839         WARN("Application gave us bad destination rectangle for Blt without a clipper set.\n");
840         ret = WINEDDERR_INVALIDRECT;
841         goto release;
842     }
843
844     /* Now handle negative values in the rectangles. Warning: only supported for now
845     in the 'simple' cases (ie not in any stretching / rotation cases).
846
847     First, the case where nothing is to be done.
848     */
849     if (((xdst.bottom <= 0) || (xdst.right <= 0)         ||
850           (xdst.top    >= (int) This->currentDesc.Height) ||
851           (xdst.left   >= (int) This->currentDesc.Width)) ||
852           ((Src != NULL) &&
853           ((xsrc.bottom <= 0) || (xsrc.right <= 0)     ||
854           (xsrc.top >= (int) Src->currentDesc.Height) ||
855           (xsrc.left >= (int) Src->currentDesc.Width))  ))
856     {
857         TRACE("Nothing to be done !\n");
858         goto release;
859     }
860
861     /* The easy case : the source-less blits.... */
862     if (Src == NULL)
863     {
864         RECT full_rect;
865         RECT temp_rect; /* No idea if intersect rect can be the same as one of the source rect */
866
867         full_rect.left   = 0;
868         full_rect.top    = 0;
869         full_rect.right  = This->currentDesc.Width;
870         full_rect.bottom = This->currentDesc.Height;
871         IntersectRect(&temp_rect, &full_rect, &xdst);
872         xdst = temp_rect;
873     }
874     else
875     {
876         /* Only handle clipping on the destination rectangle */
877         int clip_horiz = (xdst.left < 0) || (xdst.right  > (int) This->currentDesc.Width );
878         int clip_vert  = (xdst.top  < 0) || (xdst.bottom > (int) This->currentDesc.Height);
879         if (clip_vert || clip_horiz)
880         {
881             /* Now check if this is a special case or not... */
882             if ((((xdst.bottom - xdst.top ) != (xsrc.bottom - xsrc.top )) && clip_vert ) ||
883                    (((xdst.right  - xdst.left) != (xsrc.right  - xsrc.left)) && clip_horiz) ||
884                    (Flags & WINEDDBLT_DDFX))
885             {
886                 WARN("Out of screen rectangle in special case. Not handled right now.\n");
887                 goto release;
888             }
889
890             if (clip_horiz)
891             {
892                 if (xdst.left < 0) { xsrc.left -= xdst.left; xdst.left = 0; }
893                 if (xdst.right > This->currentDesc.Width)
894                 {
895                     xsrc.right -= (xdst.right - (int) This->currentDesc.Width);
896                     xdst.right = (int) This->currentDesc.Width;
897                 }
898             }
899             if (clip_vert)
900             {
901                 if (xdst.top < 0)
902                 {
903                     xsrc.top -= xdst.top;
904                     xdst.top = 0;
905                 }
906                 if (xdst.bottom > This->currentDesc.Height)
907                 {
908                     xsrc.bottom -= (xdst.bottom - (int) This->currentDesc.Height);
909                     xdst.bottom = (int) This->currentDesc.Height;
910                 }
911             }
912             /* And check if after clipping something is still to be done... */
913             if ((xdst.bottom <= 0)   || (xdst.right <= 0)       ||
914                  (xdst.top   >= (int) This->currentDesc.Height)  ||
915                  (xdst.left  >= (int) This->currentDesc.Width)   ||
916                  (xsrc.bottom <= 0)   || (xsrc.right <= 0)       ||
917                  (xsrc.top >= (int) Src->currentDesc.Height)     ||
918                  (xsrc.left >= (int) Src->currentDesc.Width))
919             {
920                 TRACE("Nothing to be done after clipping !\n");
921                 goto release;
922             }
923         }
924     }
925
926     bpp = This->bytesPerPixel;
927     srcheight = xsrc.bottom - xsrc.top;
928     srcwidth = xsrc.right - xsrc.left;
929     dstheight = xdst.bottom - xdst.top;
930     dstwidth = xdst.right - xdst.left;
931     width = (xdst.right - xdst.left) * bpp;
932
933     assert(width <= dlock.Pitch);
934
935     dbuf = (BYTE*)dlock.pBits+(xdst.top*dlock.Pitch)+(xdst.left*bpp);
936
937     if (Flags & WINEDDBLT_WAIT)
938     {
939         Flags &= ~WINEDDBLT_WAIT;
940     }
941     if (Flags & WINEDDBLT_ASYNC)
942     {
943         static BOOL displayed = FALSE;
944         if (!displayed)
945             FIXME("Can't handle WINEDDBLT_ASYNC flag right now.\n");
946         displayed = TRUE;
947         Flags &= ~WINEDDBLT_ASYNC;
948     }
949     if (Flags & WINEDDBLT_DONOTWAIT)
950     {
951         /* WINEDDBLT_DONOTWAIT appeared in DX7 */
952         static BOOL displayed = FALSE;
953         if (!displayed)
954             FIXME("Can't handle WINEDDBLT_DONOTWAIT flag right now.\n");
955         displayed = TRUE;
956         Flags &= ~WINEDDBLT_DONOTWAIT;
957     }
958
959     /* First, all the 'source-less' blits */
960     if (Flags & WINEDDBLT_COLORFILL)
961     {
962         ret = _Blt_ColorFill(dbuf, dstwidth, dstheight, bpp,
963                              dlock.Pitch, DDBltFx->u5.dwFillColor);
964         Flags &= ~WINEDDBLT_COLORFILL;
965     }
966
967     if (Flags & WINEDDBLT_DEPTHFILL)
968     {
969         FIXME("DDBLT_DEPTHFILL needs to be implemented!\n");
970     }
971     if (Flags & WINEDDBLT_ROP)
972     {
973         /* Catch some degenerate cases here */
974         switch(DDBltFx->dwROP)
975         {
976             case BLACKNESS:
977                 ret = _Blt_ColorFill(dbuf,dstwidth,dstheight,bpp,dlock.Pitch,0);
978                 break;
979                 case 0xAA0029: /* No-op */
980                     break;
981             case WHITENESS:
982                 ret = _Blt_ColorFill(dbuf,dstwidth,dstheight,bpp,dlock.Pitch,~0);
983                 break;
984                 case SRCCOPY: /* well, we do that below ? */
985                     break;
986             default:
987                 FIXME("Unsupported raster op: %08x  Pattern: %p\n", DDBltFx->dwROP, DDBltFx->u5.lpDDSPattern);
988                 goto error;
989         }
990         Flags &= ~WINEDDBLT_ROP;
991     }
992     if (Flags & WINEDDBLT_DDROPS)
993     {
994         FIXME("\tDdraw Raster Ops: %08x  Pattern: %p\n", DDBltFx->dwDDROP, DDBltFx->u5.lpDDSPattern);
995     }
996     /* Now the 'with source' blits */
997     if (Src)
998     {
999         LPBYTE sbase;
1000         int sx, xinc, sy, yinc;
1001
1002         if (!dstwidth || !dstheight) /* hmm... stupid program ? */
1003             goto release;
1004         sbase = (BYTE*)slock.pBits+(xsrc.top*slock.Pitch)+xsrc.left*bpp;
1005         xinc = (srcwidth << 16) / dstwidth;
1006         yinc = (srcheight << 16) / dstheight;
1007
1008         if (!Flags)
1009         {
1010             /* No effects, we can cheat here */
1011             if (dstwidth == srcwidth)
1012             {
1013                 if (dstheight == srcheight)
1014                 {
1015                     /* No stretching in either direction. This needs to be as
1016                     * fast as possible */
1017                     sbuf = sbase;
1018
1019                     /* check for overlapping surfaces */
1020                     if (SrcSurface != iface || xdst.top < xsrc.top ||
1021                         xdst.right <= xsrc.left || xsrc.right <= xdst.left)
1022                     {
1023                         /* no overlap, or dst above src, so copy from top downwards */
1024                         for (y = 0; y < dstheight; y++)
1025                         {
1026                             memcpy(dbuf, sbuf, width);
1027                             sbuf += slock.Pitch;
1028                             dbuf += dlock.Pitch;
1029                         }
1030                     }
1031                     else if (xdst.top > xsrc.top)  /* copy from bottom upwards */
1032                     {
1033                         sbuf += (slock.Pitch*dstheight);
1034                         dbuf += (dlock.Pitch*dstheight);
1035                         for (y = 0; y < dstheight; y++)
1036                         {
1037                             sbuf -= slock.Pitch;
1038                             dbuf -= dlock.Pitch;
1039                             memcpy(dbuf, sbuf, width);
1040                         }
1041                     }
1042                     else /* src and dst overlapping on the same line, use memmove */
1043                     {
1044                         for (y = 0; y < dstheight; y++)
1045                         {
1046                             memmove(dbuf, sbuf, width);
1047                             sbuf += slock.Pitch;
1048                             dbuf += dlock.Pitch;
1049                         }
1050                     }
1051                 } else {
1052                     /* Stretching in Y direction only */
1053                     for (y = sy = 0; y < dstheight; y++, sy += yinc) {
1054                         sbuf = sbase + (sy >> 16) * slock.Pitch;
1055                         memcpy(dbuf, sbuf, width);
1056                         dbuf += dlock.Pitch;
1057                     }
1058                 }
1059             }
1060             else
1061             {
1062                 /* Stretching in X direction */
1063                 int last_sy = -1;
1064                 for (y = sy = 0; y < dstheight; y++, sy += yinc)
1065                 {
1066                     sbuf = sbase + (sy >> 16) * slock.Pitch;
1067
1068                     if ((sy >> 16) == (last_sy >> 16))
1069                     {
1070                         /* this sourcerow is the same as last sourcerow -
1071                         * copy already stretched row
1072                         */
1073                         memcpy(dbuf, dbuf - dlock.Pitch, width);
1074                     }
1075                     else
1076                     {
1077 #define STRETCH_ROW(type) { \
1078                         type *s = (type *) sbuf, *d = (type *) dbuf; \
1079                         for (x = sx = 0; x < dstwidth; x++, sx += xinc) \
1080                         d[x] = s[sx >> 16]; \
1081                         break; }
1082
1083                         switch(bpp)
1084                         {
1085                             case 1: STRETCH_ROW(BYTE)
1086                                     case 2: STRETCH_ROW(WORD)
1087                                             case 4: STRETCH_ROW(DWORD)
1088                             case 3:
1089                             {
1090                                 LPBYTE s,d = dbuf;
1091                                 for (x = sx = 0; x < dstwidth; x++, sx+= xinc)
1092                                 {
1093                                     DWORD pixel;
1094
1095                                     s = sbuf+3*(sx>>16);
1096                                     pixel = s[0]|(s[1]<<8)|(s[2]<<16);
1097                                     d[0] = (pixel    )&0xff;
1098                                     d[1] = (pixel>> 8)&0xff;
1099                                     d[2] = (pixel>>16)&0xff;
1100                                     d+=3;
1101                                 }
1102                                 break;
1103                             }
1104                             default:
1105                                 FIXME("Stretched blit not implemented for bpp %d!\n", bpp*8);
1106                                 ret = WINED3DERR_NOTAVAILABLE;
1107                                 goto error;
1108                         }
1109 #undef STRETCH_ROW
1110                     }
1111                     dbuf += dlock.Pitch;
1112                     last_sy = sy;
1113                 }
1114             }
1115         }
1116         else
1117         {
1118             LONG dstyinc = dlock.Pitch, dstxinc = bpp;
1119             DWORD keylow = 0xFFFFFFFF, keyhigh = 0, keymask = 0xFFFFFFFF;
1120             DWORD destkeylow = 0x0, destkeyhigh = 0xFFFFFFFF, destkeymask = 0xFFFFFFFF;
1121             if (Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYDEST | WINEDDBLT_KEYSRCOVERRIDE | WINEDDBLT_KEYDESTOVERRIDE))
1122             {
1123                 /* The color keying flags are checked for correctness in ddraw */
1124                 if (Flags & WINEDDBLT_KEYSRC)
1125                 {
1126                     keylow  = Src->SrcBltCKey.dwColorSpaceLowValue;
1127                     keyhigh = Src->SrcBltCKey.dwColorSpaceHighValue;
1128                 }
1129                 else  if (Flags & WINEDDBLT_KEYSRCOVERRIDE)
1130                 {
1131                     keylow  = DDBltFx->ddckSrcColorkey.dwColorSpaceLowValue;
1132                     keyhigh = DDBltFx->ddckSrcColorkey.dwColorSpaceHighValue;
1133                 }
1134
1135                 if (Flags & WINEDDBLT_KEYDEST)
1136                 {
1137                     /* Destination color keys are taken from the source surface ! */
1138                     destkeylow  = Src->DestBltCKey.dwColorSpaceLowValue;
1139                     destkeyhigh = Src->DestBltCKey.dwColorSpaceHighValue;
1140                 }
1141                 else if (Flags & WINEDDBLT_KEYDESTOVERRIDE)
1142                 {
1143                     destkeylow  = DDBltFx->ddckDestColorkey.dwColorSpaceLowValue;
1144                     destkeyhigh = DDBltFx->ddckDestColorkey.dwColorSpaceHighValue;
1145                 }
1146
1147                 if(bpp == 1)
1148                 {
1149                     keymask = 0xff;
1150                 }
1151                 else
1152                 {
1153                     keymask = sEntry->redMask   |
1154                             sEntry->greenMask |
1155                             sEntry->blueMask;
1156                 }
1157                 Flags &= ~(WINEDDBLT_KEYSRC | WINEDDBLT_KEYDEST | WINEDDBLT_KEYSRCOVERRIDE | WINEDDBLT_KEYDESTOVERRIDE);
1158             }
1159
1160             if (Flags & WINEDDBLT_DDFX)
1161             {
1162                 LPBYTE dTopLeft, dTopRight, dBottomLeft, dBottomRight, tmp;
1163                 LONG tmpxy;
1164                 dTopLeft     = dbuf;
1165                 dTopRight    = dbuf+((dstwidth-1)*bpp);
1166                 dBottomLeft  = dTopLeft+((dstheight-1)*dlock.Pitch);
1167                 dBottomRight = dBottomLeft+((dstwidth-1)*bpp);
1168
1169                 if (DDBltFx->dwDDFX & WINEDDBLTFX_ARITHSTRETCHY)
1170                 {
1171                     /* I don't think we need to do anything about this flag */
1172                     WARN("Flags=DDBLT_DDFX nothing done for WINEDDBLTFX_ARITHSTRETCHY\n");
1173                 }
1174                 if (DDBltFx->dwDDFX & WINEDDBLTFX_MIRRORLEFTRIGHT)
1175                 {
1176                     tmp          = dTopRight;
1177                     dTopRight    = dTopLeft;
1178                     dTopLeft     = tmp;
1179                     tmp          = dBottomRight;
1180                     dBottomRight = dBottomLeft;
1181                     dBottomLeft  = tmp;
1182                     dstxinc = dstxinc *-1;
1183                 }
1184                 if (DDBltFx->dwDDFX & WINEDDBLTFX_MIRRORUPDOWN)
1185                 {
1186                     tmp          = dTopLeft;
1187                     dTopLeft     = dBottomLeft;
1188                     dBottomLeft  = tmp;
1189                     tmp          = dTopRight;
1190                     dTopRight    = dBottomRight;
1191                     dBottomRight = tmp;
1192                     dstyinc = dstyinc *-1;
1193                 }
1194                 if (DDBltFx->dwDDFX & WINEDDBLTFX_NOTEARING)
1195                 {
1196                     /* I don't think we need to do anything about this flag */
1197                     WARN("Flags=DDBLT_DDFX nothing done for WINEDDBLTFX_NOTEARING\n");
1198                 }
1199                 if (DDBltFx->dwDDFX & WINEDDBLTFX_ROTATE180)
1200                 {
1201                     tmp          = dBottomRight;
1202                     dBottomRight = dTopLeft;
1203                     dTopLeft     = tmp;
1204                     tmp          = dBottomLeft;
1205                     dBottomLeft  = dTopRight;
1206                     dTopRight    = tmp;
1207                     dstxinc = dstxinc * -1;
1208                     dstyinc = dstyinc * -1;
1209                 }
1210                 if (DDBltFx->dwDDFX & WINEDDBLTFX_ROTATE270)
1211                 {
1212                     tmp          = dTopLeft;
1213                     dTopLeft     = dBottomLeft;
1214                     dBottomLeft  = dBottomRight;
1215                     dBottomRight = dTopRight;
1216                     dTopRight    = tmp;
1217                     tmpxy   = dstxinc;
1218                     dstxinc = dstyinc;
1219                     dstyinc = tmpxy;
1220                     dstxinc = dstxinc * -1;
1221                 }
1222                 if (DDBltFx->dwDDFX & WINEDDBLTFX_ROTATE90)
1223                 {
1224                     tmp          = dTopLeft;
1225                     dTopLeft     = dTopRight;
1226                     dTopRight    = dBottomRight;
1227                     dBottomRight = dBottomLeft;
1228                     dBottomLeft  = tmp;
1229                     tmpxy   = dstxinc;
1230                     dstxinc = dstyinc;
1231                     dstyinc = tmpxy;
1232                     dstyinc = dstyinc * -1;
1233                 }
1234                 if (DDBltFx->dwDDFX & WINEDDBLTFX_ZBUFFERBASEDEST)
1235                 {
1236                     /* I don't think we need to do anything about this flag */
1237                     WARN("Flags=WINEDDBLT_DDFX nothing done for WINEDDBLTFX_ZBUFFERBASEDEST\n");
1238                 }
1239                 dbuf = dTopLeft;
1240                 Flags &= ~(WINEDDBLT_DDFX);
1241             }
1242
1243 #define COPY_COLORKEY_FX(type) { \
1244             type *s, *d = (type *) dbuf, *dx, tmp; \
1245             for (y = sy = 0; y < dstheight; y++, sy += yinc) { \
1246             s = (type*)(sbase + (sy >> 16) * slock.Pitch); \
1247             dx = d; \
1248             for (x = sx = 0; x < dstwidth; x++, sx += xinc) { \
1249             tmp = s[sx >> 16]; \
1250             if (((tmp & keymask) < keylow || (tmp & keymask) > keyhigh) && \
1251             ((dx[0] & destkeymask) >= destkeylow && (dx[0] & destkeymask) <= destkeyhigh)) { \
1252             dx[0] = tmp; \
1253         } \
1254             dx = (type*)(((LPBYTE)dx)+dstxinc); \
1255         } \
1256             d = (type*)(((LPBYTE)d)+dstyinc); \
1257         } \
1258             break; }
1259
1260             switch (bpp) {
1261                 case 1: COPY_COLORKEY_FX(BYTE)
1262                         case 2: COPY_COLORKEY_FX(WORD)
1263                                 case 4: COPY_COLORKEY_FX(DWORD)
1264                 case 3:
1265                 {
1266                     LPBYTE s,d = dbuf, dx;
1267                     for (y = sy = 0; y < dstheight; y++, sy += yinc)
1268                     {
1269                         sbuf = sbase + (sy >> 16) * slock.Pitch;
1270                         dx = d;
1271                         for (x = sx = 0; x < dstwidth; x++, sx+= xinc)
1272                         {
1273                             DWORD pixel, dpixel = 0;
1274                             s = sbuf+3*(sx>>16);
1275                             pixel = s[0]|(s[1]<<8)|(s[2]<<16);
1276                             dpixel = dx[0]|(dx[1]<<8)|(dx[2]<<16);
1277                             if (((pixel & keymask) < keylow || (pixel & keymask) > keyhigh) &&
1278                                   ((dpixel & keymask) >= destkeylow || (dpixel & keymask) <= keyhigh))
1279                             {
1280                                 dx[0] = (pixel    )&0xff;
1281                                 dx[1] = (pixel>> 8)&0xff;
1282                                 dx[2] = (pixel>>16)&0xff;
1283                             }
1284                             dx+= dstxinc;
1285                         }
1286                         d += dstyinc;
1287                     }
1288                     break;
1289                 }
1290                 default:
1291                     FIXME("%s color-keyed blit not implemented for bpp %d!\n",
1292                           (Flags & WINEDDBLT_KEYSRC) ? "Source" : "Destination", bpp*8);
1293                     ret = WINED3DERR_NOTAVAILABLE;
1294                     goto error;
1295 #undef COPY_COLORKEY_FX
1296             }
1297         }
1298     }
1299
1300 error:
1301     if (Flags && FIXME_ON(d3d_surface))
1302     {
1303         FIXME("\tUnsupported flags: %08x\n", Flags);
1304     }
1305
1306 release:
1307     IWineD3DSurface_UnlockRect(iface);
1308     if (SrcSurface && SrcSurface != iface) IWineD3DSurface_UnlockRect(SrcSurface);
1309     return ret;
1310 }
1311
1312 /*****************************************************************************
1313  * IWineD3DSurface::BltFast, SW emulation version
1314  *
1315  * This is the software implementation of BltFast, as used by GDI surfaces
1316  * and as a fallback for OpenGL surfaces. This code is taken from the old
1317  * DirectDraw code, and was originally written by TransGaming.
1318  *
1319  * Params:
1320  *  dstx:
1321  *  dsty:
1322  *  Source: Source surface to copy from
1323  *  rsrc: Source rectangle
1324  *  trans: Some Flags
1325  *
1326  * Returns:
1327  *  WINED3D_OK on success
1328  *
1329  *****************************************************************************/
1330 HRESULT WINAPI
1331 IWineD3DBaseSurfaceImpl_BltFast(IWineD3DSurface *iface,
1332                                 DWORD dstx,
1333                                 DWORD dsty,
1334                                 IWineD3DSurface *Source,
1335                                 RECT *rsrc,
1336                                 DWORD trans)
1337 {
1338     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
1339     IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) Source;
1340
1341     int                 bpp, w, h, x, y;
1342     WINED3DLOCKED_RECT  dlock,slock;
1343     HRESULT             ret = WINED3D_OK;
1344     RECT                rsrc2;
1345     RECT                lock_src, lock_dst, lock_union;
1346     BYTE                *sbuf, *dbuf;
1347     const StaticPixelFormatDesc *sEntry, *dEntry;
1348
1349     if (TRACE_ON(d3d_surface))
1350     {
1351         TRACE("(%p)->(%d,%d,%p,%p,%08x)\n", This,dstx,dsty,Src,rsrc,trans);
1352
1353         if (rsrc)
1354         {
1355             TRACE("\tsrcrect: %dx%d-%dx%d\n",rsrc->left,rsrc->top,
1356                   rsrc->right,rsrc->bottom);
1357         }
1358         else
1359         {
1360             TRACE(" srcrect: NULL\n");
1361         }
1362     }
1363
1364     if ((This->Flags & SFLAG_LOCKED) ||
1365          ((Src != NULL) && (Src->Flags & SFLAG_LOCKED)))
1366     {
1367         WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
1368         return WINEDDERR_SURFACEBUSY;
1369     }
1370
1371     if (!rsrc)
1372     {
1373         WARN("rsrc is NULL!\n");
1374         rsrc = &rsrc2;
1375         rsrc->left = 0;
1376         rsrc->top = 0;
1377         rsrc->right = Src->currentDesc.Width;
1378         rsrc->bottom = Src->currentDesc.Height;
1379     }
1380
1381     /* Check source rect for validity. Copied from normal Blt. Fixes Baldur's Gate.*/
1382     if ((rsrc->bottom > Src->currentDesc.Height) || (rsrc->bottom < 0) ||
1383          (rsrc->top    > Src->currentDesc.Height) || (rsrc->top    < 0) ||
1384          (rsrc->left   > Src->currentDesc.Width)  || (rsrc->left   < 0) ||
1385          (rsrc->right  > Src->currentDesc.Width)  || (rsrc->right  < 0) ||
1386          (rsrc->right  < rsrc->left)              || (rsrc->bottom < rsrc->top))
1387     {
1388         WARN("Application gave us bad source rectangle for BltFast.\n");
1389         return WINEDDERR_INVALIDRECT;
1390     }
1391
1392     h = rsrc->bottom - rsrc->top;
1393     if (h > This->currentDesc.Height-dsty) h = This->currentDesc.Height-dsty;
1394     if (h > Src->currentDesc.Height-rsrc->top) h=Src->currentDesc.Height-rsrc->top;
1395     if (h <= 0) return WINEDDERR_INVALIDRECT;
1396
1397     w = rsrc->right - rsrc->left;
1398     if (w > This->currentDesc.Width-dstx) w = This->currentDesc.Width-dstx;
1399     if (w > Src->currentDesc.Width-rsrc->left) w = Src->currentDesc.Width-rsrc->left;
1400     if (w <= 0) return WINEDDERR_INVALIDRECT;
1401
1402     /* Now compute the locking rectangle... */
1403     lock_src.left = rsrc->left;
1404     lock_src.top = rsrc->top;
1405     lock_src.right = lock_src.left + w;
1406     lock_src.bottom = lock_src.top + h;
1407
1408     lock_dst.left = dstx;
1409     lock_dst.top = dsty;
1410     lock_dst.right = dstx + w;
1411     lock_dst.bottom = dsty + h;
1412
1413     bpp = This->bytesPerPixel;
1414
1415     /* We need to lock the surfaces, or we won't get refreshes when done. */
1416     if (Src == This)
1417     {
1418         int pitch;
1419
1420         UnionRect(&lock_union, &lock_src, &lock_dst);
1421
1422         /* Lock the union of the two rectangles */
1423         ret = IWineD3DSurface_LockRect(iface, &dlock, &lock_union, 0);
1424         if(ret != WINED3D_OK) goto error;
1425
1426         pitch = dlock.Pitch;
1427         slock.Pitch = dlock.Pitch;
1428
1429         /* Since slock was originally copied from this surface's description, we can just reuse it */
1430         assert(This->resource.allocatedMemory != NULL);
1431         sbuf = This->resource.allocatedMemory + lock_src.top * pitch + lock_src.left * bpp;
1432         dbuf = This->resource.allocatedMemory + lock_dst.top * pitch + lock_dst.left * bpp;
1433         sEntry = getFormatDescEntry(Src->resource.format, NULL, NULL);
1434         dEntry = sEntry;
1435     }
1436     else
1437     {
1438         ret = IWineD3DSurface_LockRect(Source, &slock, &lock_src, WINED3DLOCK_READONLY);
1439         if(ret != WINED3D_OK) goto error;
1440         ret = IWineD3DSurface_LockRect(iface, &dlock, &lock_dst, 0);
1441         if(ret != WINED3D_OK) goto error;
1442
1443         sbuf = slock.pBits;
1444         dbuf = dlock.pBits;
1445         TRACE("Dst is at %p, Src is at %p\n", dbuf, sbuf);
1446
1447         sEntry = getFormatDescEntry(Src->resource.format, NULL, NULL);
1448         dEntry = getFormatDescEntry(This->resource.format, NULL, NULL);
1449     }
1450
1451     /* Handle first the FOURCC surfaces... */
1452     if (sEntry->isFourcc && dEntry->isFourcc)
1453     {
1454         TRACE("Fourcc -> Fourcc copy\n");
1455         if (trans)
1456             FIXME("trans arg not supported when a FOURCC surface is involved\n");
1457         if (dstx || dsty)
1458             FIXME("offset for destination surface is not supported\n");
1459         if (Src->resource.format != This->resource.format)
1460         {
1461             FIXME("FOURCC->FOURCC copy only supported for the same type of surface\n");
1462             ret = WINED3DERR_WRONGTEXTUREFORMAT;
1463             goto error;
1464         }
1465         /* FIXME: Watch out that the size is correct for FOURCC surfaces */
1466         memcpy(dbuf, sbuf, This->resource.size);
1467         goto error;
1468     }
1469     if (sEntry->isFourcc && !dEntry->isFourcc)
1470     {
1471         /* TODO: Use the libtxc_dxtn.so shared library to do
1472          * software decompression
1473          */
1474         ERR("DXTC decompression not supported by now\n");
1475         goto error;
1476     }
1477
1478     if (trans & (WINEDDBLTFAST_SRCCOLORKEY | WINEDDBLTFAST_DESTCOLORKEY))
1479     {
1480         DWORD keylow, keyhigh;
1481         TRACE("Color keyed copy\n");
1482         if (trans & WINEDDBLTFAST_SRCCOLORKEY)
1483         {
1484             keylow  = Src->SrcBltCKey.dwColorSpaceLowValue;
1485             keyhigh = Src->SrcBltCKey.dwColorSpaceHighValue;
1486         }
1487         else
1488         {
1489             /* I'm not sure if this is correct */
1490             FIXME("WINEDDBLTFAST_DESTCOLORKEY not fully supported yet.\n");
1491             keylow  = This->DestBltCKey.dwColorSpaceLowValue;
1492             keyhigh = This->DestBltCKey.dwColorSpaceHighValue;
1493         }
1494
1495 #define COPYBOX_COLORKEY(type) { \
1496         type *d, *s, tmp; \
1497         s = (type *) sbuf; \
1498         d = (type *) dbuf; \
1499         for (y = 0; y < h; y++) { \
1500         for (x = 0; x < w; x++) { \
1501         tmp = s[x]; \
1502         if (tmp < keylow || tmp > keyhigh) d[x] = tmp; \
1503     } \
1504         s = (type *)((BYTE *)s + slock.Pitch); \
1505         d = (type *)((BYTE *)d + dlock.Pitch); \
1506     } \
1507         break; \
1508     }
1509
1510         switch (bpp) {
1511             case 1: COPYBOX_COLORKEY(BYTE)
1512                     case 2: COPYBOX_COLORKEY(WORD)
1513                             case 4: COPYBOX_COLORKEY(DWORD)
1514             case 3:
1515             {
1516                 BYTE *d, *s;
1517                 DWORD tmp;
1518                 s = sbuf;
1519                 d = dbuf;
1520                 for (y = 0; y < h; y++)
1521                 {
1522                     for (x = 0; x < w * 3; x += 3)
1523                     {
1524                         tmp = (DWORD)s[x] + ((DWORD)s[x + 1] << 8) + ((DWORD)s[x + 2] << 16);
1525                         if (tmp < keylow || tmp > keyhigh)
1526                         {
1527                             d[x + 0] = s[x + 0];
1528                             d[x + 1] = s[x + 1];
1529                             d[x + 2] = s[x + 2];
1530                         }
1531                     }
1532                     s += slock.Pitch;
1533                     d += dlock.Pitch;
1534                 }
1535                 break;
1536             }
1537             default:
1538                 FIXME("Source color key blitting not supported for bpp %d\n",bpp*8);
1539                 ret = WINED3DERR_NOTAVAILABLE;
1540                 goto error;
1541         }
1542 #undef COPYBOX_COLORKEY
1543         TRACE("Copy Done\n");
1544     }
1545     else
1546     {
1547         int width = w * bpp;
1548         TRACE("NO color key copy\n");
1549         for (y = 0; y < h; y++)
1550         {
1551             /* This is pretty easy, a line for line memcpy */
1552             memcpy(dbuf, sbuf, width);
1553             sbuf += slock.Pitch;
1554             dbuf += dlock.Pitch;
1555         }
1556         TRACE("Copy done\n");
1557     }
1558
1559 error:
1560     if (Src == This)
1561     {
1562         IWineD3DSurface_UnlockRect(iface);
1563     }
1564     else
1565     {
1566         IWineD3DSurface_UnlockRect(iface);
1567         IWineD3DSurface_UnlockRect(Source);
1568     }
1569
1570     return ret;
1571 }
1572
1573 HRESULT WINAPI IWineD3DBaseSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags)
1574 {
1575     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1576
1577     TRACE("(%p) : rect@%p flags(%08x), output lockedRect@%p, memory@%p\n",
1578           This, pRect, Flags, pLockedRect, This->resource.allocatedMemory);
1579
1580     pLockedRect->Pitch = IWineD3DSurface_GetPitch(iface);
1581
1582     if (NULL == pRect)
1583     {
1584         pLockedRect->pBits = This->resource.allocatedMemory;
1585         This->lockedRect.left   = 0;
1586         This->lockedRect.top    = 0;
1587         This->lockedRect.right  = This->currentDesc.Width;
1588         This->lockedRect.bottom = This->currentDesc.Height;
1589
1590         TRACE("Locked Rect (%p) = l %d, t %d, r %d, b %d\n",
1591               &This->lockedRect, This->lockedRect.left, This->lockedRect.top,
1592               This->lockedRect.right, This->lockedRect.bottom);
1593     }
1594     else
1595     {
1596         TRACE("Lock Rect (%p) = l %d, t %d, r %d, b %d\n",
1597               pRect, pRect->left, pRect->top, pRect->right, pRect->bottom);
1598
1599         /* DXTn textures are based on compressed blocks of 4x4 pixels, each
1600          * 16 bytes large (8 bytes in case of DXT1). Because of that Pitch has
1601          * slightly different meaning compared to regular textures. For DXTn
1602          * textures Pitch is the size of a row of blocks, 4 high and "width"
1603          * long. The x offset is calculated differently as well, since moving 4
1604          * pixels to the right actually moves an entire 4x4 block to right, ie
1605          * 16 bytes (8 in case of DXT1). */
1606         if (This->resource.format == WINED3DFMT_DXT1)
1607         {
1608             pLockedRect->pBits = This->resource.allocatedMemory + (pLockedRect->Pitch * pRect->top / 4) + (pRect->left * 2);
1609         }
1610         else if (This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
1611                     This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5)
1612         {
1613             pLockedRect->pBits = This->resource.allocatedMemory + (pLockedRect->Pitch * pRect->top / 4) + (pRect->left * 4);
1614         }
1615         else
1616         {
1617             pLockedRect->pBits = This->resource.allocatedMemory +
1618                     (pLockedRect->Pitch * pRect->top) +
1619                     (pRect->left * This->bytesPerPixel);
1620         }
1621         This->lockedRect.left   = pRect->left;
1622         This->lockedRect.top    = pRect->top;
1623         This->lockedRect.right  = pRect->right;
1624         This->lockedRect.bottom = pRect->bottom;
1625     }
1626
1627     /* No dirtifying is needed for this surface implementation */
1628     TRACE("returning memory@%p, pitch(%d)\n", pLockedRect->pBits, pLockedRect->Pitch);
1629
1630     return WINED3D_OK;
1631 }
1632
1633 void WINAPI IWineD3DBaseSurfaceImpl_BindTexture(IWineD3DSurface *iface) {
1634     ERR("Should not be called on base texture\n");
1635     return;
1636 }