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