Prevent crash when no URL is specified.
[wine] / dlls / ddraw / dsurface / dib.c
1 /*              DIBSection DirectDrawSurface driver
2  *
3  * Copyright 1997-2000 Marcus Meissner
4  * Copyright 1998-2000 Lionel Ulmer
5  * Copyright 2000-2001 TransGaming Technologies Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23
24 #include <assert.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
30 #include "winerror.h"
31 #include "wine/debug.h"
32 #include "ddraw_private.h"
33 #include "d3d_private.h"
34 #include "dsurface/main.h"
35 #include "dsurface/dib.h"
36
37 WINE_DEFAULT_DEBUG_CHANNEL(ddraw);
38
39 /* FIXME */
40 extern HBITMAP DIB_CreateDIBSection( HDC hdc, const BITMAPINFO *bmi, UINT usage, VOID **bits,
41                                      HANDLE section, DWORD offset, DWORD ovr_pitch );
42
43 static IDirectDrawSurface7Vtbl DIB_IDirectDrawSurface7_VTable;
44
45 /* Return the width of a DIB bitmap in bytes. DIB bitmap data is 32-bit aligned. */
46 inline static int get_dib_width_bytes( int width, int depth )
47 {
48     int words;
49
50     switch(depth)
51     {
52     case 1:  words = (width + 31) / 32; break;
53     case 4:  words = (width + 7) / 8; break;
54     case 8:  words = (width + 3) / 4; break;
55     case 15:
56     case 16: words = (width + 1) / 2; break;
57     case 24: words = (width * 3 + 3)/4; break;
58     default:
59         WARN("(%d): Unsupported depth\n", depth );
60         /* fall through */
61     case 32: words = width; break;
62     }
63     return 4 * words;
64 }
65
66
67 static HRESULT create_dib(IDirectDrawSurfaceImpl* This)
68 {
69     BITMAPINFO* b_info;
70     UINT usage;
71     HDC ddc;
72     DIB_DirectDrawSurfaceImpl* priv = This->private;
73
74     assert(This->surface_desc.lpSurface != NULL);
75
76     switch (This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount)
77     {
78     case 16:
79     case 32:
80         /* Allocate extra space to store the RGB bit masks. */
81         b_info = (BITMAPINFO*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
82                                         sizeof(BITMAPINFOHEADER)
83                                         + 3 * sizeof(DWORD));
84         break;
85
86     case 24:
87         b_info = (BITMAPINFO*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
88                                         sizeof(BITMAPINFOHEADER));
89         break;
90
91     default:
92         /* Allocate extra space for a palette. */
93         b_info = (BITMAPINFO*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
94                                         sizeof(BITMAPINFOHEADER)
95                                         + sizeof(RGBQUAD)
96                                         * (1 << This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount));
97         break;
98     }
99
100     b_info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
101     b_info->bmiHeader.biWidth = This->surface_desc.dwWidth;
102     b_info->bmiHeader.biHeight = -This->surface_desc.dwHeight;
103     b_info->bmiHeader.biPlanes = 1;
104     b_info->bmiHeader.biBitCount = This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount;
105
106     if ((This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount != 16)
107         && (This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount != 32))
108         b_info->bmiHeader.biCompression = BI_RGB;
109     else
110         b_info->bmiHeader.biCompression = BI_BITFIELDS;
111
112     b_info->bmiHeader.biSizeImage
113         = (This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount / 8)
114         * This->surface_desc.dwWidth * This->surface_desc.dwHeight;
115
116     b_info->bmiHeader.biXPelsPerMeter = 0;
117     b_info->bmiHeader.biYPelsPerMeter = 0;
118     b_info->bmiHeader.biClrUsed = 0;
119     b_info->bmiHeader.biClrImportant = 0;
120
121     if (!This->surface_desc.u1.lPitch) {
122         /* This can't happen, right? */
123         /* or use GDI_GetObj to get it from the created DIB? */
124         This->surface_desc.u1.lPitch = get_dib_width_bytes(b_info->bmiHeader.biWidth, b_info->bmiHeader.biBitCount);
125         This->surface_desc.dwFlags |= DDSD_PITCH;
126     }
127     
128     switch (This->surface_desc.u4.ddpfPixelFormat.u1.dwRGBBitCount)
129     {
130     case 16:
131     case 32:
132     {
133         DWORD *masks = (DWORD *) &(b_info->bmiColors);
134
135         usage = 0;
136         masks[0] = This->surface_desc.u4.ddpfPixelFormat.u2.dwRBitMask;
137         masks[1] = This->surface_desc.u4.ddpfPixelFormat.u3.dwGBitMask;
138         masks[2] = This->surface_desc.u4.ddpfPixelFormat.u4.dwBBitMask;
139     }
140     break;
141
142     case 24:
143         /* Nothing to do */
144         usage = DIB_RGB_COLORS;
145         break;
146
147     default:
148         /* Don't know palette */
149         usage = 0;
150         break;
151     }
152
153     ddc = CreateDCA("DISPLAY", NULL, NULL, NULL);
154     if (ddc == 0)
155     {
156         HeapFree(GetProcessHeap(), 0, b_info);
157         return HRESULT_FROM_WIN32(GetLastError());
158     }
159
160     priv->dib.DIBsection
161         = DIB_CreateDIBSection(ddc, b_info, usage, &(priv->dib.bitmap_data), 0,
162                                (DWORD)This->surface_desc.lpSurface,
163                                This->surface_desc.u1.lPitch);
164     DeleteDC(ddc);
165     if (!priv->dib.DIBsection) {
166         ERR("CreateDIBSection failed!\n");
167         HeapFree(GetProcessHeap(), 0, b_info);
168         return HRESULT_FROM_WIN32(GetLastError());
169     }
170
171     TRACE("DIBSection at : %p\n", priv->dib.bitmap_data);
172
173     if (!This->surface_desc.lpSurface) {
174         This->surface_desc.lpSurface = priv->dib.bitmap_data;
175         This->surface_desc.dwFlags |= DDSD_LPSURFACE;
176     }
177
178     HeapFree(GetProcessHeap(), 0, b_info);
179
180     /* I don't think it's worth checking for this. */
181     if (priv->dib.bitmap_data != This->surface_desc.lpSurface)
182         ERR("unexpected error creating DirectDrawSurface DIB section\n");
183
184     /* this seems like a good place to put the handle for HAL driver use */
185     This->global_more.hKernelSurface = (ULONG_PTR)priv->dib.DIBsection;
186
187     return S_OK;
188 }
189
190 void DIB_DirectDrawSurface_final_release(IDirectDrawSurfaceImpl* This)
191 {
192     DIB_DirectDrawSurfaceImpl* priv = This->private;
193
194     DeleteObject(priv->dib.DIBsection);
195
196     if (!priv->dib.client_memory)
197         VirtualFree(This->surface_desc.lpSurface, 0, MEM_RELEASE);
198
199     Main_DirectDrawSurface_final_release(This);
200 }
201
202 HRESULT DIB_DirectDrawSurface_duplicate_surface(IDirectDrawSurfaceImpl* This,
203                                                 LPDIRECTDRAWSURFACE7* ppDup)
204 {
205     return DIB_DirectDrawSurface_Create(This->ddraw_owner,
206                                         &This->surface_desc, ppDup, NULL);
207 }
208
209 HRESULT DIB_DirectDrawSurface_Construct(IDirectDrawSurfaceImpl *This,
210                                         IDirectDrawImpl *pDD,
211                                         const DDSURFACEDESC2 *pDDSD)
212 {
213     HRESULT hr;
214     DIB_DirectDrawSurfaceImpl* priv = This->private;
215
216     TRACE("(%p)->(%p,%p)\n",This,pDD,pDDSD);
217     hr = Main_DirectDrawSurface_Construct(This, pDD, pDDSD);
218     if (FAILED(hr)) return hr;
219
220     ICOM_INIT_INTERFACE(This, IDirectDrawSurface7,
221                         DIB_IDirectDrawSurface7_VTable);
222
223     This->final_release = DIB_DirectDrawSurface_final_release;
224     This->duplicate_surface = DIB_DirectDrawSurface_duplicate_surface;
225     This->flip_data = DIB_DirectDrawSurface_flip_data;
226
227     This->get_dc     = DIB_DirectDrawSurface_get_dc;
228     This->release_dc = DIB_DirectDrawSurface_release_dc;
229     This->hDC = NULL;
230
231     This->set_palette    = DIB_DirectDrawSurface_set_palette;
232     This->update_palette = DIB_DirectDrawSurface_update_palette;
233
234     TRACE("(%ldx%ld, pitch=%ld)\n",
235           This->surface_desc.dwWidth, This->surface_desc.dwHeight,
236           This->surface_desc.u1.lPitch);
237     /* XXX load dwWidth and dwHeight from pDD if they are not specified? */
238
239     if (This->surface_desc.dwFlags & DDSD_LPSURFACE)
240     {
241         /* "Client memory": it is managed by the application. */
242         /* XXX What if lPitch is not set? Use dwWidth or fail? */
243
244         priv->dib.client_memory = TRUE;
245     }
246     else
247     {
248         if (!(This->surface_desc.dwFlags & DDSD_PITCH))
249         {
250             int pitch = This->surface_desc.u1.lPitch;
251             if (pitch % 8 != 0)
252                 pitch += 8 - (pitch % 8);
253         }
254         /* XXX else: how should lPitch be verified? */
255
256         This->surface_desc.dwFlags |= DDSD_LPSURFACE;
257
258         /* Ensure that DDSD_PITCH is respected for DDPF_FOURCC surfaces too */
259         if (This->surface_desc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC && !(This->surface_desc.dwFlags & DDSD_PITCH)) {
260             This->surface_desc.lpSurface
261                 = VirtualAlloc(NULL, This->surface_desc.u1.dwLinearSize, MEM_COMMIT, PAGE_READWRITE);
262             This->surface_desc.dwFlags |= DDSD_LINEARSIZE;
263         } else {
264             This->surface_desc.lpSurface
265                 = VirtualAlloc(NULL, This->surface_desc.u1.lPitch
266                            * This->surface_desc.dwHeight + 4, /* The + 4 here is for dumb games reading after the end of the surface
267                                                                  when reading the last byte / half using word access */
268                            MEM_COMMIT, PAGE_READWRITE);
269             This->surface_desc.dwFlags |= DDSD_PITCH;
270         }
271
272         if (This->surface_desc.lpSurface == NULL)
273         {
274             Main_DirectDrawSurface_final_release(This);
275             return HRESULT_FROM_WIN32(GetLastError());
276         }
277
278         priv->dib.client_memory = FALSE;
279     }
280
281     hr = create_dib(This);
282     if (FAILED(hr))
283     {
284         if (!priv->dib.client_memory)
285             VirtualFree(This->surface_desc.lpSurface, 0, MEM_RELEASE);
286
287         Main_DirectDrawSurface_final_release(This);
288
289         return hr;
290     }
291
292     return DD_OK;
293 }
294
295 /* Not an API */
296 HRESULT DIB_DirectDrawSurface_Create(IDirectDrawImpl *pDD,
297                                      const DDSURFACEDESC2 *pDDSD,
298                                      LPDIRECTDRAWSURFACE7 *ppSurf,
299                                      IUnknown *pUnkOuter)
300 {
301     IDirectDrawSurfaceImpl* This;
302     HRESULT hr;
303     assert(pUnkOuter == NULL);
304
305     This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
306                      sizeof(*This) + sizeof(DIB_DirectDrawSurfaceImpl));
307     if (This == NULL) return E_OUTOFMEMORY;
308
309     This->private = (DIB_DirectDrawSurfaceImpl*)(This+1);
310
311     hr = DIB_DirectDrawSurface_Construct(This, pDD, pDDSD);
312     if (FAILED(hr))
313         HeapFree(GetProcessHeap(), 0, This);
314     else
315         *ppSurf = ICOM_INTERFACE(This, IDirectDrawSurface7);
316
317     return hr;
318
319 }
320
321 /* AddAttachedSurface: generic */
322 /* AddOverlayDirtyRect: generic, unimplemented */
323
324 static HRESULT _Blt_ColorFill(
325     LPBYTE buf, int width, int height, int bpp, LONG lPitch, DWORD color
326 ) {
327     int x, y;
328     LPBYTE first;
329
330     /* Do first row */
331
332 #define COLORFILL_ROW(type) { \
333     type *d = (type *) buf; \
334     for (x = 0; x < width; x++) \
335         d[x] = (type) color; \
336     break; \
337 }
338
339     switch(bpp) {
340     case 1: COLORFILL_ROW(BYTE)
341     case 2: COLORFILL_ROW(WORD)
342     case 3: { BYTE *d = (BYTE *) buf;
343               for (x = 0; x < width; x++,d+=3) {
344                 d[0] = (color    ) & 0xFF;
345                 d[1] = (color>> 8) & 0xFF;
346                 d[2] = (color>>16) & 0xFF;
347               }
348               break;}
349     case 4: COLORFILL_ROW(DWORD)
350     default:
351         FIXME("Color fill not implemented for bpp %d!\n", bpp*8);
352         return DDERR_UNSUPPORTED;
353     }
354
355 #undef COLORFILL_ROW
356
357     /* Now copy first row */
358     first = buf;
359     for (y = 1; y < height; y++) {
360         buf += lPitch;
361         memcpy(buf, first, width * bpp);
362     }
363     return DD_OK;
364 }
365
366 static void ComputeShifts(DWORD mask, DWORD* lshift, DWORD* rshift)
367 {
368     int pos = 0;
369     int bits = 0;
370     *lshift = 0;
371     *rshift = 0;
372     
373     if (!mask)
374         return;
375     
376     while(!(mask & (1 << pos)))
377         pos++; 
378     
379     while(mask & (1 << (pos+bits)))
380         bits++;
381     
382     *lshift = pos;
383     *rshift = 8 - bits;
384 }
385
386 /* This is used to factorize the decompression between the Blt and BltFast code */
387 static void DoDXTCDecompression(const DDSURFACEDESC2 *sdesc, const DDSURFACEDESC2 *ddesc)
388 {
389     DWORD rs,rb,rm;
390     DWORD gs,gb,gm;
391     DWORD bs,bb,bm;
392     DWORD as,ab,am;
393
394     if (!s3tc_initialized) {
395         /* FIXME: We may fake this by rendering the texture into the framebuffer using OpenGL functions and reading back
396          *        the framebuffer. This will be slow and somewhat ugly. */ 
397         FIXME("Manual S3TC decompression is not supported in native mode\n");
398         return;
399     }
400     
401     rm = ddesc->u4.ddpfPixelFormat.u2.dwRBitMask;
402     ComputeShifts(rm, &rs, &rb);
403     gm = ddesc->u4.ddpfPixelFormat.u3.dwGBitMask;
404     ComputeShifts(gm, &gs, &gb);
405     bm = ddesc->u4.ddpfPixelFormat.u4.dwBBitMask;
406     ComputeShifts(bm, &bs, &bb);
407     am = ddesc->u4.ddpfPixelFormat.u5.dwRGBAlphaBitMask;
408     ComputeShifts(am, &as, &ab);
409     if (sdesc->u4.ddpfPixelFormat.dwFourCC == MAKE_FOURCC('D','X','T','1')) {
410         int is16 = ddesc->u4.ddpfPixelFormat.u1.dwRGBBitCount == 16;
411         int pitch = ddesc->u1.lPitch;
412         int width = ddesc->dwWidth;
413         int height = ddesc->dwHeight;
414         int x,y;
415         char* dst = (char*) ddesc->lpSurface;
416         char* src = (char*) sdesc->lpSurface;
417         for (x = 0; x < width; x++)
418             for (y =0; y < height; y++) {
419                 DWORD pixel = 0;
420                 BYTE data[4];
421                 (*fetch_2d_texel_rgba_dxt1)(width, src, x, y, data);
422                 pixel = 0;
423                 pixel |= ((data[0] >> rb) << rs) & rm;
424                 pixel |= ((data[1] >> gb) << gs) & gm;
425                 pixel |= ((data[2] >> bb) << bs) & bm;
426                 pixel |= ((data[3] >> ab) << as) & am;
427                 if (is16)
428                     *((WORD*)(dst+y*pitch+x*(is16?2:4))) = pixel;
429                 else
430                     *((DWORD*)(dst+y*pitch+x*(is16?2:4))) = pixel;
431             }
432     } else if (sdesc->u4.ddpfPixelFormat.dwFourCC == MAKE_FOURCC('D','X','T','3')) {
433         int is16 = ddesc->u4.ddpfPixelFormat.u1.dwRGBBitCount == 16;
434         int pitch = ddesc->u1.lPitch;
435         int width = ddesc->dwWidth;
436         int height = ddesc->dwHeight;
437         int x,y;
438         char* dst = (char*) ddesc->lpSurface;
439         char* src = (char*) sdesc->lpSurface;
440         for (x = 0; x < width; x++)
441             for (y =0; y < height; y++) {
442                 DWORD pixel = 0;
443                 BYTE data[4];
444                 (*fetch_2d_texel_rgba_dxt3)(width, src, x, y, data);
445                 pixel = 0;
446                 pixel |= ((data[0] >> rb) << rs) & rm;
447                 pixel |= ((data[1] >> gb) << gs) & gm;
448                 pixel |= ((data[2] >> bb) << bs) & bm;
449                 pixel |= ((data[3] >> ab) << as) & am;
450                 if (is16)
451                     *((WORD*)(dst+y*pitch+x*(is16?2:4))) = pixel;
452                 else
453                     *((DWORD*)(dst+y*pitch+x*(is16?2:4))) = pixel;
454             }
455     } else if (sdesc->u4.ddpfPixelFormat.dwFourCC == MAKE_FOURCC('D','X','T','5')) {
456         int is16 = ddesc->u4.ddpfPixelFormat.u1.dwRGBBitCount == 16;
457         int pitch = ddesc->u1.lPitch;
458         int width = ddesc->dwWidth;
459         int height = ddesc->dwHeight;
460         int x,y;
461         char* dst = (char*) ddesc->lpSurface;
462         char* src = (char*) sdesc->lpSurface;
463         for (x = 0; x < width; x++)
464             for (y =0; y < height; y++) {
465                 DWORD pixel = 0;
466                 BYTE data[4];
467                 (*fetch_2d_texel_rgba_dxt5)(width, src, x, y, data);
468                 pixel = 0;
469                 pixel |= ((data[0] >> rb) << rs) & rm;
470                 pixel |= ((data[1] >> gb) << gs) & gm;
471                 pixel |= ((data[2] >> bb) << bs) & bm;
472                 pixel |= ((data[3] >> ab) << as) & am;
473                 if (is16)
474                     *((WORD*)(dst+y*pitch+x*(is16?2:4))) = pixel;
475                 else
476                     *((DWORD*)(dst+y*pitch+x*(is16?2:4))) = pixel;
477             }
478     }
479 #if 0 /* Usefull for debugging */
480     {
481         static int idx;
482         char texname[255];
483         FILE* f;
484         sprintf(texname, "dxt_%d.pnm", idx++);
485         f = fopen(texname,"w");
486         DDRAW_dump_surface_to_disk(This, f, 1);
487         fclose(f);
488     }
489 #endif
490 }
491
492 HRESULT WINAPI
493 DIB_DirectDrawSurface_Blt(LPDIRECTDRAWSURFACE7 iface, LPRECT rdst,
494                           LPDIRECTDRAWSURFACE7 src, LPRECT rsrc,
495                           DWORD dwFlags, LPDDBLTFX lpbltfx)
496 {
497     IDirectDrawSurfaceImpl *This = (IDirectDrawSurfaceImpl *)iface;
498     RECT                xdst,xsrc;
499     DDSURFACEDESC2      ddesc,sdesc;
500     HRESULT             ret = DD_OK;
501     int bpp, srcheight, srcwidth, dstheight, dstwidth, width;
502     int x, y;
503     LPBYTE dbuf, sbuf;
504     
505     TRACE("(%p)->(%p,%p,%p,%08lx,%p)\n", This,rdst,src,rsrc,dwFlags,lpbltfx);
506
507     if (TRACE_ON(ddraw)) {
508         if (rdst) TRACE("\tdestrect :%ldx%ld-%ldx%ld\n",rdst->left,rdst->top,rdst->right,rdst->bottom);
509         if (rsrc) TRACE("\tsrcrect  :%ldx%ld-%ldx%ld\n",rsrc->left,rsrc->top,rsrc->right,rsrc->bottom);
510         TRACE("\tflags: ");
511         DDRAW_dump_DDBLT(dwFlags);
512         if (dwFlags & DDBLT_DDFX) {
513             TRACE("\tblitfx: ");
514             DDRAW_dump_DDBLTFX(lpbltfx->dwDDFX);
515         }
516     }
517
518     if ((This->locked) || ((src != NULL) && (((IDirectDrawSurfaceImpl *)src)->locked))) {
519         WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
520         return DDERR_SURFACEBUSY;
521     }
522
523     /* First, check if the possible override function handles this case */
524     if (This->aux_blt != NULL) {
525         if (This->aux_blt(This, rdst, src, rsrc, dwFlags, lpbltfx) == DD_OK) return DD_OK;
526     }
527
528     DD_STRUCT_INIT(&ddesc);
529     DD_STRUCT_INIT(&sdesc);
530
531     sdesc.dwSize = sizeof(sdesc);
532     if (src) IDirectDrawSurface7_Lock(src, NULL, &sdesc, DDLOCK_READONLY, 0);
533     ddesc.dwSize = sizeof(ddesc);
534     IDirectDrawSurface7_Lock(iface,NULL,&ddesc,DDLOCK_WRITEONLY,0);
535
536     if ((sdesc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC) &&
537         (ddesc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC)) {
538         if (sdesc.u4.ddpfPixelFormat.dwFourCC != sdesc.u4.ddpfPixelFormat.dwFourCC) {
539             FIXME("FOURCC->FOURCC copy only supported for the same type of surface\n");
540             ret = DDERR_INVALIDPIXELFORMAT;
541             goto release;
542         }
543         memcpy(ddesc.lpSurface, sdesc.lpSurface, ddesc.u1.dwLinearSize);
544         goto release;
545     }
546
547     if ((sdesc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC) &&
548         (!(ddesc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC))) {
549         DoDXTCDecompression(&sdesc, &ddesc);
550         goto release;
551     }
552     
553     if (rdst) {
554         memcpy(&xdst,rdst,sizeof(xdst));
555     } else {
556         xdst.top        = 0;
557         xdst.bottom     = ddesc.dwHeight;
558         xdst.left       = 0;
559         xdst.right      = ddesc.dwWidth;
560     }
561
562     if (rsrc) {
563         memcpy(&xsrc,rsrc,sizeof(xsrc));
564     } else {
565         if (src) {
566             xsrc.top    = 0;
567             xsrc.bottom = sdesc.dwHeight;
568             xsrc.left   = 0;
569             xsrc.right  = sdesc.dwWidth;
570         } else {
571             memset(&xsrc,0,sizeof(xsrc));
572         }
573     }
574
575     /* First check for the validity of source / destination rectangles. This was
576        verified using a test application + by MSDN.
577     */
578     if ((src != NULL) &&
579         ((xsrc.bottom > sdesc.dwHeight) || (xsrc.bottom < 0) ||
580          (xsrc.top > sdesc.dwHeight) || (xsrc.top < 0) ||
581          (xsrc.left > sdesc.dwWidth) || (xsrc.left < 0) ||
582          (xsrc.right > sdesc.dwWidth) || (xsrc.right < 0) ||
583          (xsrc.right < xsrc.left) || (xsrc.bottom < xsrc.top))) {
584         WARN("Application gave us bad source rectangle for Blt.\n");
585         return DDERR_INVALIDRECT;
586     }
587     /* For the Destination rect, it can be out of bounds on the condition that a clipper
588        is set for the given surface.
589     */
590     if ((This->clipper == NULL) &&
591         ((xdst.bottom > ddesc.dwHeight) || (xdst.bottom < 0) ||
592          (xdst.top > ddesc.dwHeight) || (xdst.top < 0) ||
593          (xdst.left > ddesc.dwWidth) || (xdst.left < 0) ||
594          (xdst.right > ddesc.dwWidth) || (xdst.right < 0) ||
595          (xdst.right < xdst.left) || (xdst.bottom < xdst.top))) {
596         WARN("Application gave us bad destination rectangle for Blt without a clipper set.\n");
597         return DDERR_INVALIDRECT;
598     }
599     
600     /* Now handle negative values in the rectangles. Warning: only supported for now
601        in the 'simple' cases (ie not in any stretching / rotation cases).
602
603        First, the case where nothing is to be done.
604     */
605     if (((xdst.bottom <= 0) || (xdst.right <= 0) || (xdst.top >= (int) ddesc.dwHeight) || (xdst.left >= (int) ddesc.dwWidth)) ||
606         ((src != NULL) &&
607          ((xsrc.bottom <= 0) || (xsrc.right <= 0) || (xsrc.top >= (int) sdesc.dwHeight) || (xsrc.left >= (int) sdesc.dwWidth))))
608     {
609         TRACE("Nothing to be done !\n");
610         goto release;
611     }
612
613     /* The easy case : the source-less blits.... */
614     if (src == NULL) {
615         RECT full_rect;
616         RECT temp_rect; /* No idea if intersect rect can be the same as one of the source rect */
617
618         full_rect.left   = 0;
619         full_rect.top    = 0;
620         full_rect.right  = ddesc.dwWidth;
621         full_rect.bottom = ddesc.dwHeight;
622         IntersectRect(&temp_rect, &full_rect, &xdst);
623         xdst = temp_rect;
624     } else {
625         /* Only handle clipping on the destination rectangle */
626         int clip_horiz = (xdst.left < 0) || (xdst.right  > (int) ddesc.dwWidth );
627         int clip_vert  = (xdst.top  < 0) || (xdst.bottom > (int) ddesc.dwHeight);
628         if (clip_vert || clip_horiz) {
629             /* Now check if this is a special case or not... */
630             if ((((xdst.bottom - xdst.top ) != (xsrc.bottom - xsrc.top )) && clip_vert ) ||
631                 (((xdst.right  - xdst.left) != (xsrc.right  - xsrc.left)) && clip_horiz) ||
632                 (dwFlags & DDBLT_DDFX)) {
633                 WARN("Out of screen rectangle in special case. Not handled right now.\n");
634                 goto release;
635             }
636
637             if (clip_horiz) {
638               if (xdst.left < 0) { xsrc.left -= xdst.left; xdst.left = 0; }
639               if (xdst.right > ddesc.dwWidth) { xsrc.right -= (xdst.right - (int) ddesc.dwWidth); xdst.right = (int) ddesc.dwWidth; }
640             }
641             if (clip_vert) {
642                 if (xdst.top < 0) { xsrc.top -= xdst.top; xdst.top = 0; }
643                 if (xdst.bottom > ddesc.dwHeight) { xsrc.bottom -= (xdst.bottom - (int) ddesc.dwHeight); xdst.bottom = (int) ddesc.dwHeight; }
644             }
645             /* And check if after clipping something is still to be done... */
646             if ((xdst.bottom <= 0) || (xdst.right <= 0) || (xdst.top >= (int) ddesc.dwHeight) || (xdst.left >= (int) ddesc.dwWidth) ||
647                 (xsrc.bottom <= 0) || (xsrc.right <= 0) || (xsrc.top >= (int) sdesc.dwHeight) || (xsrc.left >= (int) sdesc.dwWidth)) {
648                 TRACE("Nothing to be done after clipping !\n");
649                 goto release;
650             }
651         }
652     }
653
654     bpp = GET_BPP(ddesc);
655     srcheight = xsrc.bottom - xsrc.top;
656     srcwidth = xsrc.right - xsrc.left;
657     dstheight = xdst.bottom - xdst.top;
658     dstwidth = xdst.right - xdst.left;
659     width = (xdst.right - xdst.left) * bpp;
660
661     assert(width <= ddesc.u1.lPitch);
662
663     dbuf = (BYTE*)ddesc.lpSurface+(xdst.top*ddesc.u1.lPitch)+(xdst.left*bpp);
664
665     if (dwFlags & (DDBLT_WAIT|DDBLT_ASYNC))
666     {
667         static BOOL displayed = FALSE;
668         if (!displayed)
669         {
670             FIXME("dwFlags DDBLT_WAIT and/or DDBLT_ASYNC: can't handle right now.\n");
671             displayed = TRUE;
672         }
673         dwFlags &= ~(DDBLT_WAIT|DDBLT_ASYNC);
674     }
675
676     /* First, all the 'source-less' blits */
677     if (dwFlags & DDBLT_COLORFILL) {
678         ret = _Blt_ColorFill(dbuf, dstwidth, dstheight, bpp,
679                              ddesc.u1.lPitch, lpbltfx->u5.dwFillColor);
680         dwFlags &= ~DDBLT_COLORFILL;
681     }
682
683     if (dwFlags & DDBLT_DEPTHFILL)
684         FIXME("DDBLT_DEPTHFILL needs to be implemented!\n");
685     if (dwFlags & DDBLT_ROP) {
686         /* Catch some degenerate cases here */
687         switch(lpbltfx->dwROP) {
688         case BLACKNESS:
689             ret = _Blt_ColorFill(dbuf,dstwidth,dstheight,bpp,ddesc.u1.lPitch,0);
690             break;
691         case 0xAA0029: /* No-op */
692             break;
693         case WHITENESS:
694             ret = _Blt_ColorFill(dbuf,dstwidth,dstheight,bpp,ddesc.u1.lPitch,~0);
695             break;
696         case SRCCOPY: /* well, we do that below ? */
697             break;
698         default:
699             FIXME("Unsupported raster op: %08lx  Pattern: %p\n", lpbltfx->dwROP, lpbltfx->u5.lpDDSPattern);
700             goto error;
701         }
702         dwFlags &= ~DDBLT_ROP;
703     }
704     if (dwFlags & DDBLT_DDROPS) {
705         FIXME("\tDdraw Raster Ops: %08lx  Pattern: %p\n", lpbltfx->dwDDROP, lpbltfx->u5.lpDDSPattern);
706     }
707     /* Now the 'with source' blits */
708     if (src) {
709         LPBYTE sbase;
710         int sx, xinc, sy, yinc;
711
712         if (!dstwidth || !dstheight) /* hmm... stupid program ? */
713             goto release;
714         sbase = (BYTE*)sdesc.lpSurface+(xsrc.top*sdesc.u1.lPitch)+xsrc.left*bpp;
715         xinc = (srcwidth << 16) / dstwidth;
716         yinc = (srcheight << 16) / dstheight;
717
718         if (!dwFlags) {
719             /* No effects, we can cheat here */
720             if (dstwidth == srcwidth) {
721                 if (dstheight == srcheight) {
722                     /* No stretching in either direction. This needs to be as
723                      * fast as possible */
724                     sbuf = sbase;
725
726                     /* check for overlapping surfaces */
727                     if (src != iface || xdst.top < xsrc.top ||
728                         xdst.right <= xsrc.left || xsrc.right <= xdst.left)
729                     {
730                         /* no overlap, or dst above src, so copy from top downwards */
731                         for (y = 0; y < dstheight; y++)
732                         {
733                             memcpy(dbuf, sbuf, width);
734                             sbuf += sdesc.u1.lPitch;
735                             dbuf += ddesc.u1.lPitch;
736                         }
737                     }
738                     else if (xdst.top > xsrc.top)  /* copy from bottom upwards */
739                     {
740                         sbuf += (sdesc.u1.lPitch*dstheight);
741                         dbuf += (ddesc.u1.lPitch*dstheight);
742                         for (y = 0; y < dstheight; y++)
743                         {
744                             sbuf -= sdesc.u1.lPitch;
745                             dbuf -= ddesc.u1.lPitch;
746                             memcpy(dbuf, sbuf, width);
747                         }
748                     }
749                     else /* src and dst overlapping on the same line, use memmove */
750                     {
751                         for (y = 0; y < dstheight; y++)
752                         {
753                             memmove(dbuf, sbuf, width);
754                             sbuf += sdesc.u1.lPitch;
755                             dbuf += ddesc.u1.lPitch;
756                         }
757                     }
758                 } else {
759                     /* Stretching in Y direction only */
760                     for (y = sy = 0; y < dstheight; y++, sy += yinc) {
761                         sbuf = sbase + (sy >> 16) * sdesc.u1.lPitch;
762                         memcpy(dbuf, sbuf, width);
763                         dbuf += ddesc.u1.lPitch;
764                     }
765                 }
766             } else {
767                 /* Stretching in X direction */
768                 int last_sy = -1;
769                 for (y = sy = 0; y < dstheight; y++, sy += yinc) {
770                     sbuf = sbase + (sy >> 16) * sdesc.u1.lPitch;
771
772                     if ((sy >> 16) == (last_sy >> 16)) {
773                         /* this sourcerow is the same as last sourcerow -
774                          * copy already stretched row
775                          */
776                         memcpy(dbuf, dbuf - ddesc.u1.lPitch, width);
777                     } else {
778 #define STRETCH_ROW(type) { \
779                     type *s = (type *) sbuf, *d = (type *) dbuf; \
780                     for (x = sx = 0; x < dstwidth; x++, sx += xinc) \
781                     d[x] = s[sx >> 16]; \
782                     break; }
783
784                     switch(bpp) {
785                     case 1: STRETCH_ROW(BYTE)
786                     case 2: STRETCH_ROW(WORD)
787                     case 4: STRETCH_ROW(DWORD)
788                     case 3: {
789                         LPBYTE s,d = dbuf;
790                         for (x = sx = 0; x < dstwidth; x++, sx+= xinc) {
791                             DWORD pixel;
792
793                             s = sbuf+3*(sx>>16);
794                             pixel = s[0]|(s[1]<<8)|(s[2]<<16);
795                             d[0] = (pixel    )&0xff;
796                             d[1] = (pixel>> 8)&0xff;
797                             d[2] = (pixel>>16)&0xff;
798                             d+=3;
799                         }
800                         break;
801                     }
802                     default:
803                         FIXME("Stretched blit not implemented for bpp %d!\n", bpp*8);
804                         ret = DDERR_UNSUPPORTED;
805                         goto error;
806                     }
807 #undef STRETCH_ROW
808                     }
809                     dbuf += ddesc.u1.lPitch;
810                     last_sy = sy;
811                 }
812             }
813         } else {
814            LONG dstyinc = ddesc.u1.lPitch, dstxinc = bpp;
815            DWORD keylow = 0, keyhigh = 0;
816            if (dwFlags & (DDBLT_KEYSRC | DDBLT_KEYDEST | DDBLT_KEYSRCOVERRIDE | DDBLT_KEYDESTOVERRIDE)) {
817
818               if (dwFlags & DDBLT_KEYSRC) {
819                  keylow  = sdesc.ddckCKSrcBlt.dwColorSpaceLowValue;
820                  keyhigh = sdesc.ddckCKSrcBlt.dwColorSpaceHighValue;
821               } else if (dwFlags & DDBLT_KEYDEST){
822                  keylow  = ddesc.ddckCKDestBlt.dwColorSpaceLowValue;
823                  keyhigh = ddesc.ddckCKDestBlt.dwColorSpaceHighValue;
824               } else if (dwFlags & DDBLT_KEYSRCOVERRIDE) {
825                  keylow  = lpbltfx->ddckSrcColorkey.dwColorSpaceLowValue;
826                  keyhigh = lpbltfx->ddckSrcColorkey.dwColorSpaceHighValue;
827               } else {
828                  keylow  = lpbltfx->ddckDestColorkey.dwColorSpaceLowValue;
829                  keyhigh = lpbltfx->ddckDestColorkey.dwColorSpaceHighValue;
830               }
831               dwFlags &= ~(DDBLT_KEYSRC | DDBLT_KEYDEST | DDBLT_KEYSRCOVERRIDE | DDBLT_KEYDESTOVERRIDE);
832            }
833
834            if (dwFlags & DDBLT_DDFX)  {
835               LPBYTE dTopLeft, dTopRight, dBottomLeft, dBottomRight, tmp;
836               LONG tmpxy;
837               dTopLeft     = dbuf;
838               dTopRight    = dbuf+((dstwidth-1)*bpp);
839               dBottomLeft  = dTopLeft+((dstheight-1)*ddesc.u1.lPitch);
840               dBottomRight = dBottomLeft+((dstwidth-1)*bpp);
841
842               if (lpbltfx->dwDDFX & DDBLTFX_ARITHSTRETCHY){
843                  /* I don't think we need to do anything about this flag */
844                  WARN("dwflags=DDBLT_DDFX nothing done for DDBLTFX_ARITHSTRETCHY\n");
845               }
846               if (lpbltfx->dwDDFX & DDBLTFX_MIRRORLEFTRIGHT) {
847                  tmp          = dTopRight;
848                  dTopRight    = dTopLeft;
849                  dTopLeft     = tmp;
850                  tmp          = dBottomRight;
851                  dBottomRight = dBottomLeft;
852                  dBottomLeft  = tmp;
853                  dstxinc = dstxinc *-1;
854               }
855               if (lpbltfx->dwDDFX & DDBLTFX_MIRRORUPDOWN) {
856                  tmp          = dTopLeft;
857                  dTopLeft     = dBottomLeft;
858                  dBottomLeft  = tmp;
859                  tmp          = dTopRight;
860                  dTopRight    = dBottomRight;
861                  dBottomRight = tmp;
862                  dstyinc = dstyinc *-1;
863               }
864               if (lpbltfx->dwDDFX & DDBLTFX_NOTEARING) {
865                  /* I don't think we need to do anything about this flag */
866                  WARN("dwflags=DDBLT_DDFX nothing done for DDBLTFX_NOTEARING\n");
867               }
868               if (lpbltfx->dwDDFX & DDBLTFX_ROTATE180) {
869                  tmp          = dBottomRight;
870                  dBottomRight = dTopLeft;
871                  dTopLeft     = tmp;
872                  tmp          = dBottomLeft;
873                  dBottomLeft  = dTopRight;
874                  dTopRight    = tmp;
875                  dstxinc = dstxinc * -1;
876                  dstyinc = dstyinc * -1;
877               }
878               if (lpbltfx->dwDDFX & DDBLTFX_ROTATE270) {
879                  tmp          = dTopLeft;
880                  dTopLeft     = dBottomLeft;
881                  dBottomLeft  = dBottomRight;
882                  dBottomRight = dTopRight;
883                  dTopRight    = tmp;
884                  tmpxy   = dstxinc;
885                  dstxinc = dstyinc;
886                  dstyinc = tmpxy;
887                  dstxinc = dstxinc * -1;
888               }
889               if (lpbltfx->dwDDFX & DDBLTFX_ROTATE90) {
890                  tmp          = dTopLeft;
891                  dTopLeft     = dTopRight;
892                  dTopRight    = dBottomRight;
893                  dBottomRight = dBottomLeft;
894                  dBottomLeft  = tmp;
895                  tmpxy   = dstxinc;
896                  dstxinc = dstyinc;
897                  dstyinc = tmpxy;
898                  dstyinc = dstyinc * -1;
899               }
900               if (lpbltfx->dwDDFX & DDBLTFX_ZBUFFERBASEDEST) {
901                  /* I don't think we need to do anything about this flag */
902                  WARN("dwflags=DDBLT_DDFX nothing done for DDBLTFX_ZBUFFERBASEDEST\n");
903               }
904               dbuf = dTopLeft;
905               dwFlags &= ~(DDBLT_DDFX);
906            }
907
908 #define COPY_COLORKEY_FX(type) { \
909             type *s, *d = (type *) dbuf, *dx, tmp; \
910             for (y = sy = 0; y < dstheight; y++, sy += yinc) { \
911                s = (type*)(sbase + (sy >> 16) * sdesc.u1.lPitch); \
912                dx = d; \
913                for (x = sx = 0; x < dstwidth; x++, sx += xinc) { \
914                   tmp = s[sx >> 16]; \
915                   if (tmp < keylow || tmp > keyhigh) dx[0] = tmp; \
916                   dx = (type*)(((LPBYTE)dx)+dstxinc); \
917                } \
918                d = (type*)(((LPBYTE)d)+dstyinc); \
919             } \
920             break; }
921
922             switch (bpp) {
923             case 1: COPY_COLORKEY_FX(BYTE)
924             case 2: COPY_COLORKEY_FX(WORD)
925             case 4: COPY_COLORKEY_FX(DWORD)
926             case 3: {LPBYTE s,d = dbuf, dx;
927                 for (y = sy = 0; y < dstheight; y++, sy += yinc) {
928                     sbuf = sbase + (sy >> 16) * sdesc.u1.lPitch;
929                     dx = d;
930                     for (x = sx = 0; x < dstwidth; x++, sx+= xinc) {
931                         DWORD pixel;
932                         s = sbuf+3*(sx>>16);
933                         pixel = s[0]|(s[1]<<8)|(s[2]<<16);
934                         if (pixel < keylow || pixel > keyhigh){
935                             dx[0] = (pixel    )&0xff;
936                             dx[1] = (pixel>> 8)&0xff;
937                             dx[2] = (pixel>>16)&0xff;
938                         }
939                         dx+= dstxinc;
940                     }
941                     d += dstyinc;
942                 }
943                 break;}
944             default:
945                FIXME("%s color-keyed blit not implemented for bpp %d!\n",
946                   (dwFlags & DDBLT_KEYSRC) ? "Source" : "Destination", bpp*8);
947                   ret = DDERR_UNSUPPORTED;
948                   goto error;
949 #undef COPY_COLORKEY_FX
950             }
951         }
952     }
953
954 error:
955     if (dwFlags && FIXME_ON(ddraw)) {
956         FIXME("\tUnsupported flags: ");
957         DDRAW_dump_DDBLT(dwFlags);
958     }
959
960 release:
961     IDirectDrawSurface7_Unlock(iface,NULL);
962     if (src) IDirectDrawSurface7_Unlock(src,NULL);
963     return DD_OK;
964 }
965
966 /* BltBatch: generic, unimplemented */
967
968 HRESULT WINAPI
969 DIB_DirectDrawSurface_BltFast(LPDIRECTDRAWSURFACE7 iface, DWORD dstx,
970                               DWORD dsty, LPDIRECTDRAWSURFACE7 src,
971                               LPRECT rsrc, DWORD trans)
972 {
973     IDirectDrawSurfaceImpl *This = (IDirectDrawSurfaceImpl *)iface;
974     int                 bpp, w, h, x, y;
975     DDSURFACEDESC2      ddesc,sdesc;
976     HRESULT             ret = DD_OK;
977     LPBYTE              sbuf, dbuf;
978     RECT                rsrc2;
979     RECT                lock_src, lock_dst;
980
981     if (TRACE_ON(ddraw)) {
982         TRACE("(%p)->(%ld,%ld,%p,%p,%08lx)\n",
983                 This,dstx,dsty,src,rsrc,trans
984         );
985         TRACE("\ttrans:");
986         if (FIXME_ON(ddraw))
987           DDRAW_dump_DDBLTFAST(trans);
988         if (rsrc)
989           TRACE("\tsrcrect: %ldx%ld-%ldx%ld\n",rsrc->left,rsrc->top,rsrc->right,rsrc->bottom);
990         else
991           TRACE(" srcrect: NULL\n");
992     }
993
994     if ((This->locked) || ((src != NULL) && (((IDirectDrawSurfaceImpl *)src)->locked))) {
995         WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
996         return DDERR_SURFACEBUSY;
997     }
998
999     /* First, check if the possible override function handles this case */
1000     if (This->aux_bltfast != NULL) {
1001         if (This->aux_bltfast(This, dstx, dsty, src, rsrc, trans) == DD_OK) return DD_OK;
1002     }
1003
1004     /* Get the surface description without locking to first compute the width / height */
1005     ddesc = This->surface_desc;
1006     sdesc = (ICOM_OBJECT(IDirectDrawSurfaceImpl, IDirectDrawSurface7, src))->surface_desc;
1007
1008     if (!rsrc) {
1009         WARN("rsrc is NULL!\n");
1010         rsrc = &rsrc2;
1011         rsrc->left = rsrc->top = 0;
1012         rsrc->right = sdesc.dwWidth;
1013         rsrc->bottom = sdesc.dwHeight;
1014     }
1015
1016     /* Check source rect for validity. Copied from normal Blt. Fixes Baldur's Gate.*/
1017     if ((rsrc->bottom > sdesc.dwHeight) || (rsrc->bottom < 0) ||
1018         (rsrc->top > sdesc.dwHeight) || (rsrc->top < 0) ||
1019         (rsrc->left > sdesc.dwWidth) || (rsrc->left < 0) ||
1020         (rsrc->right > sdesc.dwWidth) || (rsrc->right < 0) ||
1021         (rsrc->right < rsrc->left) || (rsrc->bottom < rsrc->top)) {
1022         WARN("Application gave us bad source rectangle for BltFast.\n");
1023         return DDERR_INVALIDRECT;
1024     }
1025  
1026     h=rsrc->bottom-rsrc->top;
1027     if (h>ddesc.dwHeight-dsty) h=ddesc.dwHeight-dsty;
1028     if (h>sdesc.dwHeight-rsrc->top) h=sdesc.dwHeight-rsrc->top;
1029     if (h<=0) return DDERR_INVALIDRECT;
1030
1031     w=rsrc->right-rsrc->left;
1032     if (w>ddesc.dwWidth-dstx) w=ddesc.dwWidth-dstx;
1033     if (w>sdesc.dwWidth-rsrc->left) w=sdesc.dwWidth-rsrc->left;
1034     if (w<=0) return DDERR_INVALIDRECT;
1035
1036     /* Now compute the locking rectangle... */
1037     lock_src.left = rsrc->left;
1038     lock_src.top = rsrc->top;
1039     lock_src.right = lock_src.left + w;
1040     lock_src.bottom = lock_src.top + h;
1041
1042     lock_dst.left = dstx;
1043     lock_dst.top = dsty;
1044     lock_dst.right = dstx + w;
1045     lock_dst.bottom = dsty + h;
1046     
1047     /* We need to lock the surfaces, or we won't get refreshes when done. */
1048     sdesc.dwSize = sizeof(sdesc);
1049     IDirectDrawSurface7_Lock(src, &lock_src, &sdesc, DDLOCK_READONLY, 0);
1050     ddesc.dwSize = sizeof(ddesc);
1051     IDirectDrawSurface7_Lock(iface, &lock_dst, &ddesc, DDLOCK_WRITEONLY, 0);
1052
1053     /* Handle first the FOURCC surfaces... */
1054     if ((sdesc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC) && (ddesc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC)) {
1055         if (trans)
1056             FIXME("trans arg not supported when a FOURCC surface is involved\n");
1057         if (dstx || dsty)
1058             FIXME("offset for destination surface is not supported\n");
1059         if (sdesc.u4.ddpfPixelFormat.dwFourCC != sdesc.u4.ddpfPixelFormat.dwFourCC) {
1060             FIXME("FOURCC->FOURCC copy only supported for the same type of surface\n");
1061             ret = DDERR_INVALIDPIXELFORMAT;
1062             goto error;
1063         }
1064         memcpy(ddesc.lpSurface, sdesc.lpSurface, ddesc.u1.dwLinearSize);
1065         goto error;
1066     }
1067     if ((sdesc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC) &&
1068         (!(ddesc.u4.ddpfPixelFormat.dwFlags & DDPF_FOURCC))) {
1069         DoDXTCDecompression(&sdesc, &ddesc);
1070         goto error;
1071     }
1072     
1073     bpp = GET_BPP(This->surface_desc);
1074     sbuf = (BYTE *) sdesc.lpSurface;
1075     dbuf = (BYTE *) ddesc.lpSurface;
1076     
1077     if (trans & (DDBLTFAST_SRCCOLORKEY | DDBLTFAST_DESTCOLORKEY)) {
1078         DWORD keylow, keyhigh;
1079         if (trans & DDBLTFAST_SRCCOLORKEY) {
1080             keylow  = sdesc.ddckCKSrcBlt.dwColorSpaceLowValue;
1081             keyhigh = sdesc.ddckCKSrcBlt.dwColorSpaceHighValue;
1082         } else {
1083             /* I'm not sure if this is correct */
1084             FIXME("DDBLTFAST_DESTCOLORKEY not fully supported yet.\n");
1085             keylow  = ddesc.ddckCKDestBlt.dwColorSpaceLowValue;
1086             keyhigh = ddesc.ddckCKDestBlt.dwColorSpaceHighValue;
1087         }
1088
1089 #define COPYBOX_COLORKEY(type) { \
1090             type *d, *s, tmp; \
1091             s = (type *) sdesc.lpSurface; \
1092             d = (type *) ddesc.lpSurface; \
1093             for (y = 0; y < h; y++) { \
1094                 for (x = 0; x < w; x++) { \
1095                     tmp = s[x]; \
1096                     if (tmp < keylow || tmp > keyhigh) d[x] = tmp; \
1097                 } \
1098                 s = (type *)((BYTE *)s + sdesc.u1.lPitch); \
1099                 d = (type *)((BYTE *)d + ddesc.u1.lPitch); \
1100             } \
1101             break; \
1102         }
1103
1104         switch (bpp) {
1105             case 1: COPYBOX_COLORKEY(BYTE)
1106             case 2: COPYBOX_COLORKEY(WORD)
1107             case 4: COPYBOX_COLORKEY(DWORD)
1108             case 3:
1109             {
1110                 BYTE *d, *s;
1111                 DWORD tmp;
1112                 s = (BYTE *) sdesc.lpSurface;
1113                 d = (BYTE *) ddesc.lpSurface;
1114                 for (y = 0; y < h; y++) {
1115                     for (x = 0; x < w * 3; x += 3) {
1116                         tmp = (DWORD)s[x] + ((DWORD)s[x + 1] << 8) + ((DWORD)s[x + 2] << 16);
1117                         if (tmp < keylow || tmp > keyhigh) {
1118                             d[x + 0] = s[x + 0];
1119                             d[x + 1] = s[x + 1];
1120                             d[x + 2] = s[x + 2];
1121                         }
1122                     }
1123                     s += sdesc.u1.lPitch;
1124                     d += ddesc.u1.lPitch;
1125                 }
1126                 break;
1127             }
1128             default:
1129                 FIXME("Source color key blitting not supported for bpp %d\n",bpp*8);
1130                 ret = DDERR_UNSUPPORTED;
1131                 goto error;
1132         }
1133 #undef COPYBOX_COLORKEY
1134     } else {
1135         int width = w * bpp;
1136
1137         for (y = 0; y < h; y++) {
1138             memcpy(dbuf, sbuf, width);
1139             sbuf += sdesc.u1.lPitch;
1140             dbuf += ddesc.u1.lPitch;
1141         }
1142     }
1143     
1144 error:
1145     IDirectDrawSurface7_Unlock(iface, &lock_dst);
1146     IDirectDrawSurface7_Unlock(src, &lock_src);
1147     return ret;
1148 }
1149
1150 /* ChangeUniquenessValue: generic */
1151 /* DeleteAttachedSurface: generic */
1152 /* EnumAttachedSurfaces: generic */
1153 /* EnumOverlayZOrders: generic, unimplemented */
1154
1155 BOOL DIB_DirectDrawSurface_flip_data(IDirectDrawSurfaceImpl* front,
1156                                      IDirectDrawSurfaceImpl* back,
1157                                      DWORD dwFlags)
1158 {
1159     DIB_DirectDrawSurfaceImpl* front_priv = front->private;
1160     DIB_DirectDrawSurfaceImpl* back_priv = back->private;
1161
1162     TRACE("(%p,%p)\n",front,back);
1163
1164     {
1165         HBITMAP tmp;
1166         tmp = front_priv->dib.DIBsection;
1167         front_priv->dib.DIBsection = back_priv->dib.DIBsection;
1168         back_priv->dib.DIBsection = tmp;
1169     }
1170
1171     {
1172         void* tmp;
1173         tmp = front_priv->dib.bitmap_data;
1174         front_priv->dib.bitmap_data = back_priv->dib.bitmap_data;
1175         back_priv->dib.bitmap_data = tmp;
1176
1177         tmp = front->surface_desc.lpSurface;
1178         front->surface_desc.lpSurface = back->surface_desc.lpSurface;
1179         back->surface_desc.lpSurface = tmp;
1180     }
1181
1182     /* client_memory should not be different, but just in case */
1183     {
1184         BOOL tmp;
1185         tmp = front_priv->dib.client_memory;
1186         front_priv->dib.client_memory = back_priv->dib.client_memory;
1187         back_priv->dib.client_memory = tmp;
1188     }
1189
1190     return Main_DirectDrawSurface_flip_data(front, back, dwFlags);
1191 }
1192
1193 /* Flip: generic */
1194 /* FreePrivateData: generic */
1195 /* GetAttachedSurface: generic */
1196 /* GetBltStatus: generic */
1197 /* GetCaps: generic (Returns the caps from This->surface_desc.) */
1198 /* GetClipper: generic */
1199 /* GetColorKey: generic */
1200
1201 HRESULT DIB_DirectDrawSurface_alloc_dc(IDirectDrawSurfaceImpl* This, HDC* phDC)
1202 {
1203     DIB_PRIV_VAR(priv, This);
1204     HDC hDC;
1205
1206     TRACE("Grabbing a DC for surface: %p\n", This);
1207
1208     hDC = CreateCompatibleDC(0);
1209     priv->dib.holdbitmap = SelectObject(hDC, priv->dib.DIBsection);
1210     if (This->palette)
1211         SelectPalette(hDC, This->palette->hpal, FALSE);
1212
1213     *phDC = hDC;
1214
1215     return S_OK;
1216 }
1217
1218 HRESULT DIB_DirectDrawSurface_free_dc(IDirectDrawSurfaceImpl* This, HDC hDC)
1219 {
1220     DIB_PRIV_VAR(priv, This);
1221
1222     TRACE("Releasing DC for surface: %p\n", This);
1223
1224     SelectObject(hDC, priv->dib.holdbitmap);
1225     DeleteDC(hDC);
1226
1227     return S_OK;
1228 }
1229
1230 HRESULT DIB_DirectDrawSurface_get_dc(IDirectDrawSurfaceImpl* This, HDC* phDC)
1231 {
1232     return DIB_DirectDrawSurface_alloc_dc(This, phDC);
1233 }
1234
1235 HRESULT DIB_DirectDrawSurface_release_dc(IDirectDrawSurfaceImpl* This, HDC hDC)
1236 {
1237     return DIB_DirectDrawSurface_free_dc(This, hDC);
1238 }
1239
1240 /* GetDDInterface: generic */
1241 /* GetFlipStatus: generic */
1242 /* GetLOD: generic */
1243 /* GetOverlayPosition: generic */
1244 /* GetPalette: generic */
1245 /* GetPixelFormat: generic */
1246 /* GetPriority: generic */
1247 /* GetPrivateData: generic */
1248 /* GetSurfaceDesc: generic */
1249 /* GetUniquenessValue: generic */
1250 /* Initialize: generic */
1251 /* IsLost: generic */
1252 /* Lock: generic with callback? */
1253 /* PageLock: generic */
1254 /* PageUnlock: generic */
1255
1256 HRESULT WINAPI
1257 DIB_DirectDrawSurface_Restore(LPDIRECTDRAWSURFACE7 iface)
1258 {
1259     TRACE("(%p)\n",iface);
1260     return DD_OK;       /* ??? */
1261 }
1262
1263 /* SetClipper: generic */
1264 /* SetColorKey: generic */
1265 /* SetLOD: generic */
1266 /* SetOverlayPosition: generic */
1267
1268 void DIB_DirectDrawSurface_set_palette(IDirectDrawSurfaceImpl* This,
1269                                        IDirectDrawPaletteImpl* pal)
1270 {
1271     if (!pal) return;
1272     if (This->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
1273         This->update_palette(This, pal,
1274                              0, pal->palNumEntries,
1275                              pal->palents);
1276 }
1277
1278 void DIB_DirectDrawSurface_update_palette(IDirectDrawSurfaceImpl* This,
1279                                           IDirectDrawPaletteImpl* pal,
1280                                           DWORD dwStart, DWORD dwCount,
1281                                           LPPALETTEENTRY palent)
1282 {
1283     RGBQUAD col[256];
1284     unsigned int n;
1285     HDC dc;
1286
1287     TRACE("updating primary palette\n");
1288     for (n=0; n<dwCount; n++) {
1289       col[n].rgbRed   = palent[n].peRed;
1290       col[n].rgbGreen = palent[n].peGreen;
1291       col[n].rgbBlue  = palent[n].peBlue;
1292       col[n].rgbReserved = 0;
1293     }
1294     This->get_dc(This, &dc);
1295     SetDIBColorTable(dc, dwStart, dwCount, col);
1296     This->release_dc(This, dc);
1297
1298     /* Propagate change to backbuffers if there are any */
1299     /* Basically this is a modification of the Flip code to find the backbuffer */
1300     /* and duplicate the palette update there as well */
1301     if ((This->surface_desc.ddsCaps.dwCaps&(DDSCAPS_FLIP|DDSCAPS_FRONTBUFFER))
1302         == (DDSCAPS_FLIP|DDSCAPS_FRONTBUFFER))
1303     {
1304         static DDSCAPS2 back_caps = { DDSCAPS_BACKBUFFER };
1305         LPDIRECTDRAWSURFACE7 tgt;
1306
1307         HRESULT hr = IDirectDrawSurface7_GetAttachedSurface(ICOM_INTERFACE(This,IDirectDrawSurface7),
1308                                                             &back_caps, &tgt);
1309         if (!FAILED(hr))
1310         {
1311             IDirectDrawSurfaceImpl* target = ICOM_OBJECT(IDirectDrawSurfaceImpl,
1312                                                          IDirectDrawSurface7,tgt);
1313             IDirectDrawSurface7_Release(tgt);
1314             target->get_dc(target, &dc);
1315             SetDIBColorTable(dc, dwStart, dwCount, col);
1316             target->release_dc(target, dc);
1317         }
1318     }
1319 }
1320
1321 /* SetPalette: generic */
1322 /* SetPriority: generic */
1323 /* SetPrivateData: generic */
1324
1325 HRESULT WINAPI
1326 DIB_DirectDrawSurface_SetSurfaceDesc(LPDIRECTDRAWSURFACE7 iface,
1327                                      LPDDSURFACEDESC2 pDDSD, DWORD dwFlags)
1328 {
1329     IDirectDrawSurfaceImpl *This = (IDirectDrawSurfaceImpl *)iface;
1330     DIB_PRIV_VAR(priv, This);
1331     HRESULT hr = DD_OK;
1332     DWORD flags = pDDSD->dwFlags;
1333
1334     if (TRACE_ON(ddraw)) {
1335         TRACE("(%p)->(%p,%08lx)\n",iface,pDDSD,dwFlags);
1336         DDRAW_dump_surface_desc(pDDSD);
1337     }
1338
1339     if (pDDSD->dwFlags & DDSD_PIXELFORMAT) {
1340         flags &= ~DDSD_PIXELFORMAT;
1341         if (flags & DDSD_LPSURFACE) {
1342             This->surface_desc.u4.ddpfPixelFormat = pDDSD->u4.ddpfPixelFormat;
1343         } else {
1344             FIXME("Change of pixel format without surface re-allocation is not supported !\n");
1345         }
1346     }
1347     if (pDDSD->dwFlags & DDSD_LPSURFACE) {
1348         HBITMAP oldbmp = priv->dib.DIBsection;
1349         LPVOID oldsurf = This->surface_desc.lpSurface;
1350         BOOL oldc = priv->dib.client_memory;
1351
1352         flags &= ~DDSD_LPSURFACE;
1353
1354         TRACE("new lpSurface=%p\n",pDDSD->lpSurface);
1355         This->surface_desc.lpSurface = pDDSD->lpSurface;
1356         priv->dib.client_memory = TRUE;
1357
1358         hr = create_dib(This);
1359         if (FAILED(hr))
1360         {
1361             priv->dib.DIBsection = oldbmp;
1362             This->surface_desc.lpSurface = oldsurf;
1363             priv->dib.client_memory = oldc;
1364             return hr;
1365         }
1366
1367         DeleteObject(oldbmp);
1368
1369         if (!oldc)
1370             VirtualFree(oldsurf, 0, MEM_RELEASE);
1371     }
1372     if (flags) {
1373         WARN("Unhandled flags : %08lx\n", flags);
1374     }
1375     return hr;
1376 }
1377
1378 /* Unlock: ???, need callback */
1379 /* UpdateOverlay: generic */
1380 /* UpdateOverlayDisplay: generic */
1381 /* UpdateOverlayZOrder: generic */
1382
1383 static IDirectDrawSurface7Vtbl DIB_IDirectDrawSurface7_VTable =
1384 {
1385     Main_DirectDrawSurface_QueryInterface,
1386     Main_DirectDrawSurface_AddRef,
1387     Main_DirectDrawSurface_Release,
1388     Main_DirectDrawSurface_AddAttachedSurface,
1389     Main_DirectDrawSurface_AddOverlayDirtyRect,
1390     DIB_DirectDrawSurface_Blt,
1391     Main_DirectDrawSurface_BltBatch,
1392     DIB_DirectDrawSurface_BltFast,
1393     Main_DirectDrawSurface_DeleteAttachedSurface,
1394     Main_DirectDrawSurface_EnumAttachedSurfaces,
1395     Main_DirectDrawSurface_EnumOverlayZOrders,
1396     Main_DirectDrawSurface_Flip,
1397     Main_DirectDrawSurface_GetAttachedSurface,
1398     Main_DirectDrawSurface_GetBltStatus,
1399     Main_DirectDrawSurface_GetCaps,
1400     Main_DirectDrawSurface_GetClipper,
1401     Main_DirectDrawSurface_GetColorKey,
1402     Main_DirectDrawSurface_GetDC,
1403     Main_DirectDrawSurface_GetFlipStatus,
1404     Main_DirectDrawSurface_GetOverlayPosition,
1405     Main_DirectDrawSurface_GetPalette,
1406     Main_DirectDrawSurface_GetPixelFormat,
1407     Main_DirectDrawSurface_GetSurfaceDesc,
1408     Main_DirectDrawSurface_Initialize,
1409     Main_DirectDrawSurface_IsLost,
1410     Main_DirectDrawSurface_Lock,
1411     Main_DirectDrawSurface_ReleaseDC,
1412     DIB_DirectDrawSurface_Restore,
1413     Main_DirectDrawSurface_SetClipper,
1414     Main_DirectDrawSurface_SetColorKey,
1415     Main_DirectDrawSurface_SetOverlayPosition,
1416     Main_DirectDrawSurface_SetPalette,
1417     Main_DirectDrawSurface_Unlock,
1418     Main_DirectDrawSurface_UpdateOverlay,
1419     Main_DirectDrawSurface_UpdateOverlayDisplay,
1420     Main_DirectDrawSurface_UpdateOverlayZOrder,
1421     Main_DirectDrawSurface_GetDDInterface,
1422     Main_DirectDrawSurface_PageLock,
1423     Main_DirectDrawSurface_PageUnlock,
1424     DIB_DirectDrawSurface_SetSurfaceDesc,
1425     Main_DirectDrawSurface_SetPrivateData,
1426     Main_DirectDrawSurface_GetPrivateData,
1427     Main_DirectDrawSurface_FreePrivateData,
1428     Main_DirectDrawSurface_GetUniquenessValue,
1429     Main_DirectDrawSurface_ChangeUniquenessValue,
1430     Main_DirectDrawSurface_SetPriority,
1431     Main_DirectDrawSurface_GetPriority,
1432     Main_DirectDrawSurface_SetLOD,
1433     Main_DirectDrawSurface_GetLOD
1434 };