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