d3dx9: Improve traces in set_number().
[wine] / dlls / d3dx9_36 / surface.c
1 /*
2  * Copyright (C) 2009-2010 Tony Wasserka
3  * Copyright (C) 2012 Józef Kucia
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18  *
19  */
20
21 #include "wine/debug.h"
22 #include "wine/unicode.h"
23 #include "d3dx9_36_private.h"
24
25 #include "initguid.h"
26 #include "ole2.h"
27 #include "wincodec.h"
28
29 WINE_DEFAULT_DEBUG_CHANNEL(d3dx);
30
31
32 /* Wine-specific WIC GUIDs */
33 DEFINE_GUID(GUID_WineContainerFormatTga, 0x0c44fda1,0xa5c5,0x4298,0x96,0x85,0x47,0x3f,0xc1,0x7c,0xd3,0x22);
34
35 static const struct
36 {
37     const GUID *wic_guid;
38     D3DFORMAT d3dformat;
39 } wic_pixel_formats[] = {
40     { &GUID_WICPixelFormat8bppIndexed, D3DFMT_L8 },
41     { &GUID_WICPixelFormat1bppIndexed, D3DFMT_L8 },
42     { &GUID_WICPixelFormat4bppIndexed, D3DFMT_L8 },
43     { &GUID_WICPixelFormat16bppBGR555, D3DFMT_X1R5G5B5 },
44     { &GUID_WICPixelFormat16bppBGR565, D3DFMT_R5G6B5 },
45     { &GUID_WICPixelFormat24bppBGR, D3DFMT_R8G8B8 },
46     { &GUID_WICPixelFormat32bppBGR, D3DFMT_X8R8G8B8 },
47     { &GUID_WICPixelFormat32bppBGRA, D3DFMT_A8R8G8B8 }
48 };
49
50 static D3DFORMAT wic_guid_to_d3dformat(const GUID *guid)
51 {
52     int i;
53
54     for (i = 0; i < sizeof(wic_pixel_formats) / sizeof(wic_pixel_formats[0]); i++)
55     {
56         if (IsEqualGUID(wic_pixel_formats[i].wic_guid, guid))
57             return wic_pixel_formats[i].d3dformat;
58     }
59
60     return D3DFMT_UNKNOWN;
61 }
62
63 static const GUID *d3dformat_to_wic_guid(D3DFORMAT format)
64 {
65     int i;
66
67     for (i = 0; i < sizeof(wic_pixel_formats) / sizeof(wic_pixel_formats[0]); i++)
68     {
69         if (wic_pixel_formats[i].d3dformat == format)
70             return wic_pixel_formats[i].wic_guid;
71     }
72
73     return NULL;
74 }
75
76 /* dds_header.flags */
77 #define DDS_CAPS 0x1
78 #define DDS_HEIGHT 0x2
79 #define DDS_WIDTH 0x2
80 #define DDS_PITCH 0x8
81 #define DDS_PIXELFORMAT 0x1000
82 #define DDS_MIPMAPCOUNT 0x20000
83 #define DDS_LINEARSIZE 0x80000
84 #define DDS_DEPTH 0x800000
85
86 /* dds_header.caps */
87 #define DDS_CAPS_COMPLEX 0x8
88 #define DDS_CAPS_TEXTURE 0x1000
89 #define DDS_CAPS_MIPMAP 0x400000
90
91 /* dds_header.caps2 */
92 #define DDS_CAPS2_CUBEMAP 0x200
93 #define DDS_CAPS2_CUBEMAP_POSITIVEX 0x400
94 #define DDS_CAPS2_CUBEMAP_NEGATIVEX 0x800
95 #define DDS_CAPS2_CUBEMAP_POSITIVEY 0x1000
96 #define DDS_CAPS2_CUBEMAP_NEGATIVEY 0x2000
97 #define DDS_CAPS2_CUBEMAP_POSITIVEZ 0x4000
98 #define DDS_CAPS2_CUBEMAP_NEGATIVEZ 0x8000
99 #define DDS_CAPS2_CUBEMAP_ALL_FACES ( DDS_CAPS2_CUBEMAP_POSITIVEX | DDS_CAPS2_CUBEMAP_NEGATIVEX \
100                                     | DDS_CAPS2_CUBEMAP_POSITIVEY | DDS_CAPS2_CUBEMAP_NEGATIVEY \
101                                     | DDS_CAPS2_CUBEMAP_POSITIVEZ | DDS_CAPS2_CUBEMAP_NEGATIVEZ )
102 #define DDS_CAPS2_VOLUME 0x200000
103
104 /* dds_pixel_format.flags */
105 #define DDS_PF_ALPHA 0x1
106 #define DDS_PF_ALPHA_ONLY 0x2
107 #define DDS_PF_FOURCC 0x4
108 #define DDS_PF_RGB 0x40
109 #define DDS_PF_YUV 0x200
110 #define DDS_PF_LUMINANCE 0x20000
111 #define DDS_PF_BUMPDUDV 0x80000
112
113 struct dds_pixel_format
114 {
115     DWORD size;
116     DWORD flags;
117     DWORD fourcc;
118     DWORD bpp;
119     DWORD rmask;
120     DWORD gmask;
121     DWORD bmask;
122     DWORD amask;
123 };
124
125 struct dds_header
126 {
127     DWORD signature;
128     DWORD size;
129     DWORD flags;
130     DWORD height;
131     DWORD width;
132     DWORD pitch_or_linear_size;
133     DWORD depth;
134     DWORD miplevels;
135     DWORD reserved[11];
136     struct dds_pixel_format pixel_format;
137     DWORD caps;
138     DWORD caps2;
139     DWORD caps3;
140     DWORD caps4;
141     DWORD reserved2;
142 };
143
144 static D3DFORMAT dds_fourcc_to_d3dformat(DWORD fourcc)
145 {
146     int i;
147     static const DWORD known_fourcc[] = {
148         MAKEFOURCC('U','Y','V','Y'),
149         MAKEFOURCC('Y','U','Y','2'),
150         MAKEFOURCC('R','G','B','G'),
151         MAKEFOURCC('G','R','G','B'),
152         MAKEFOURCC('D','X','T','1'),
153         MAKEFOURCC('D','X','T','2'),
154         MAKEFOURCC('D','X','T','3'),
155         MAKEFOURCC('D','X','T','4'),
156         MAKEFOURCC('D','X','T','5')
157     };
158
159     for (i = 0; i < sizeof(known_fourcc) / sizeof(known_fourcc[0]); i++)
160     {
161         if (known_fourcc[i] == fourcc)
162             return fourcc;
163     }
164
165     WARN("Unknown FourCC %#x\n", fourcc);
166     return D3DFMT_UNKNOWN;
167 }
168
169 static D3DFORMAT dds_rgb_to_d3dformat(const struct dds_pixel_format *pixel_format)
170 {
171     int i;
172     static const struct {
173         DWORD bpp;
174         DWORD rmask;
175         DWORD gmask;
176         DWORD bmask;
177         DWORD amask;
178         D3DFORMAT format;
179     } rgb_pixel_formats[] = {
180         { 8, 0xe0, 0x1c, 0x03, 0, D3DFMT_R3G3B2 },
181         { 16, 0xf800, 0x07e0, 0x001f, 0x0000, D3DFMT_R5G6B5 },
182         { 16, 0x7c00, 0x03e0, 0x001f, 0x8000, D3DFMT_A1R5G5B5 },
183         { 16, 0x7c00, 0x03e0, 0x001f, 0x0000, D3DFMT_X1R5G5B5 },
184         { 16, 0x0f00, 0x00f0, 0x000f, 0xf000, D3DFMT_A4R4G4B4 },
185         { 16, 0x0f00, 0x00f0, 0x000f, 0x0000, D3DFMT_X4R4G4B4 },
186         { 16, 0x00e0, 0x001c, 0x0003, 0xff00, D3DFMT_A8R3G3B2 },
187         { 24, 0xff0000, 0x00ff00, 0x0000ff, 0x000000, D3DFMT_R8G8B8 },
188         { 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000, D3DFMT_A8R8G8B8 },
189         { 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000, D3DFMT_X8R8G8B8 },
190         { 32, 0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000, D3DFMT_A2B10G10R10 },
191         { 32, 0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000, D3DFMT_A2R10G10B10 },
192         { 32, 0x0000ffff, 0xffff0000, 0x00000000, 0x00000000, D3DFMT_G16R16 },
193         { 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000, D3DFMT_A8B8G8R8 },
194         { 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000, D3DFMT_X8B8G8R8 },
195     };
196
197     for (i = 0; i < sizeof(rgb_pixel_formats) / sizeof(rgb_pixel_formats[0]); i++)
198     {
199         if (rgb_pixel_formats[i].bpp == pixel_format->bpp
200             && rgb_pixel_formats[i].rmask == pixel_format->rmask
201             && rgb_pixel_formats[i].gmask == pixel_format->gmask
202             && rgb_pixel_formats[i].bmask == pixel_format->bmask)
203         {
204             if ((pixel_format->flags & DDS_PF_ALPHA) && rgb_pixel_formats[i].amask == pixel_format->amask)
205                 return rgb_pixel_formats[i].format;
206             if (rgb_pixel_formats[i].amask == 0)
207                 return rgb_pixel_formats[i].format;
208         }
209     }
210
211     WARN("Unknown RGB pixel format (%#x, %#x, %#x, %#x)\n",
212         pixel_format->rmask, pixel_format->gmask, pixel_format->bmask, pixel_format->amask);
213     return D3DFMT_UNKNOWN;
214 }
215
216 static D3DFORMAT dds_luminance_to_d3dformat(const struct dds_pixel_format *pixel_format)
217 {
218     if (pixel_format->bpp == 8)
219     {
220         if (pixel_format->rmask == 0xff)
221             return D3DFMT_L8;
222         if ((pixel_format->flags & DDS_PF_ALPHA) && pixel_format->rmask == 0x0f && pixel_format->amask == 0xf0)
223             return D3DFMT_A4L4;
224     }
225     if (pixel_format->bpp == 16)
226     {
227         if (pixel_format->rmask == 0xffff)
228             return D3DFMT_L16;
229         if ((pixel_format->flags & DDS_PF_ALPHA) && pixel_format->rmask == 0x00ff && pixel_format->amask == 0xff00)
230             return D3DFMT_A8L8;
231     }
232
233     WARN("Unknown luminance pixel format (bpp %#x, l %#x, a %#x)\n",
234         pixel_format->bpp, pixel_format->rmask, pixel_format->amask);
235     return D3DFMT_UNKNOWN;
236 }
237
238 static D3DFORMAT dds_alpha_to_d3dformat(const struct dds_pixel_format *pixel_format)
239 {
240     if (pixel_format->bpp == 8 && pixel_format->amask == 0xff)
241         return D3DFMT_A8;
242
243     WARN("Unknown Alpha pixel format (%#x, %#x)\n", pixel_format->bpp, pixel_format->rmask);
244     return D3DFMT_UNKNOWN;
245 }
246
247 static D3DFORMAT dds_bump_to_d3dformat(const struct dds_pixel_format *pixel_format)
248 {
249     if (pixel_format->bpp == 16 && pixel_format->rmask == 0x00ff && pixel_format->gmask == 0xff00)
250         return D3DFMT_V8U8;
251     if (pixel_format->bpp == 32 && pixel_format->rmask == 0x0000ffff && pixel_format->gmask == 0xffff0000)
252         return D3DFMT_V16U16;
253
254     WARN("Unknown bump pixel format (%#x, %#x, %#x, %#x, %#x)\n", pixel_format->bpp,
255         pixel_format->rmask, pixel_format->gmask, pixel_format->bmask, pixel_format->amask);
256     return D3DFMT_UNKNOWN;
257 }
258
259 static D3DFORMAT dds_pixel_format_to_d3dformat(const struct dds_pixel_format *pixel_format)
260 {
261     if (pixel_format->flags & DDS_PF_FOURCC)
262         return dds_fourcc_to_d3dformat(pixel_format->fourcc);
263     if (pixel_format->flags & DDS_PF_RGB)
264         return dds_rgb_to_d3dformat(pixel_format);
265     if (pixel_format->flags & DDS_PF_LUMINANCE)
266         return dds_luminance_to_d3dformat(pixel_format);
267     if (pixel_format->flags & DDS_PF_ALPHA_ONLY)
268         return dds_alpha_to_d3dformat(pixel_format);
269     if (pixel_format->flags & DDS_PF_BUMPDUDV)
270         return dds_bump_to_d3dformat(pixel_format);
271
272     WARN("Unknown pixel format (flags %#x, fourcc %#x, bpp %#x, r %#x, g %#x, b %#x, a %#x)\n",
273         pixel_format->flags, pixel_format->fourcc, pixel_format->bpp,
274         pixel_format->rmask, pixel_format->gmask, pixel_format->bmask, pixel_format->amask);
275     return D3DFMT_UNKNOWN;
276 }
277
278 static HRESULT calculate_dds_surface_size(const D3DXIMAGE_INFO *img_info,
279     UINT width, UINT height, UINT *pitch, UINT *size)
280 {
281     const PixelFormatDesc *format_desc = get_format_info(img_info->Format);
282     if (format_desc->format == D3DFMT_UNKNOWN)
283         return E_NOTIMPL;
284
285     if (format_desc->block_width != 1 || format_desc->block_height != 1)
286     {
287         *pitch = format_desc->block_byte_count
288             * max(1, (width + format_desc->block_width - 1) / format_desc->block_width);
289         *size = *pitch
290             * max(1, (height + format_desc->block_height - 1) / format_desc->block_height);
291     }
292     else
293     {
294         *pitch = width * format_desc->bytes_per_pixel;
295         *size = *pitch * height;
296     }
297
298     return D3D_OK;
299 }
300
301 /************************************************************
302 * get_image_info_from_dds
303 *
304 * Fills a D3DXIMAGE_INFO structure with information
305 * about a DDS file stored in the memory.
306 *
307 * PARAMS
308 *   buffer  [I] pointer to DDS data
309 *   length  [I] size of DDS data
310 *   info    [O] pointer to D3DXIMAGE_INFO structure
311 *
312 * RETURNS
313 *   Success: D3D_OK
314 *   Failure: D3DXERR_INVALIDDATA
315 *
316 */
317 static HRESULT get_image_info_from_dds(const void *buffer, UINT length, D3DXIMAGE_INFO *info)
318 {
319    UINT i;
320    UINT faces = 1;
321    UINT width, height, depth;
322    const struct dds_header *header = buffer;
323    UINT expected_length = 0;
324
325    if (length < sizeof(*header) || !info)
326        return D3DXERR_INVALIDDATA;
327
328    if (header->pixel_format.size != sizeof(header->pixel_format))
329        return D3DXERR_INVALIDDATA;
330
331    info->Width = header->width;
332    info->Height = header->height;
333    info->Depth = 1;
334    info->MipLevels = (header->flags & DDS_MIPMAPCOUNT) ?  header->miplevels : 1;
335
336    info->Format = dds_pixel_format_to_d3dformat(&header->pixel_format);
337    if (info->Format == D3DFMT_UNKNOWN)
338        return D3DXERR_INVALIDDATA;
339
340    TRACE("Pixel format is %#x\n", info->Format);
341
342    if (header->caps2 & DDS_CAPS2_VOLUME)
343    {
344        info->Depth = header->depth;
345        info->ResourceType = D3DRTYPE_VOLUMETEXTURE;
346    }
347    else if (header->caps2 & DDS_CAPS2_CUBEMAP)
348    {
349        DWORD face;
350        faces = 0;
351        for (face = DDS_CAPS2_CUBEMAP_POSITIVEX; face <= DDS_CAPS2_CUBEMAP_NEGATIVEZ; face <<= 1)
352        {
353            if (header->caps2 & face)
354                faces++;
355        }
356        info->ResourceType = D3DRTYPE_CUBETEXTURE;
357    }
358    else
359    {
360        info->ResourceType = D3DRTYPE_TEXTURE;
361    }
362
363    /* calculate the expected length */
364    width = info->Width;
365    height = info->Height;
366    depth = info->Depth;
367    for (i = 0; i < info->MipLevels; i++)
368    {
369        UINT pitch, size = 0;
370        calculate_dds_surface_size(info, width, height, &pitch, &size);
371        size *= depth;
372        expected_length += size;
373        width = max(1, width / 2);
374        height = max(1, height / 2);
375        depth = max(1, depth / 2);
376    }
377
378    expected_length *= faces;
379    expected_length += sizeof(*header);
380    if (length < expected_length)
381    {
382        WARN("File is too short %u, expected at least %u bytes\n", length, expected_length);
383        return D3DXERR_INVALIDDATA;
384    }
385
386    info->ImageFileFormat = D3DXIFF_DDS;
387
388    return D3D_OK;
389 }
390
391 static HRESULT load_surface_from_dds(IDirect3DSurface9 *dst_surface, const PALETTEENTRY *dst_palette,
392     const RECT *dst_rect, const void *src_data, const RECT *src_rect, DWORD filter, D3DCOLOR color_key,
393     const D3DXIMAGE_INFO *src_info)
394 {
395     UINT size;
396     UINT src_pitch;
397     const struct dds_header *header = src_data;
398     const BYTE *pixels = (BYTE *)(header + 1);
399
400     if (src_info->ResourceType != D3DRTYPE_TEXTURE)
401         return D3DXERR_INVALIDDATA;
402
403     if (FAILED(calculate_dds_surface_size(src_info, src_info->Width, src_info->Height, &src_pitch, &size)))
404         return E_NOTIMPL;
405
406     return D3DXLoadSurfaceFromMemory(dst_surface, dst_palette, dst_rect, pixels, src_info->Format,
407         src_pitch, NULL, src_rect, filter, color_key);
408 }
409
410 HRESULT load_volume_from_dds(IDirect3DVolume9 *dst_volume, const PALETTEENTRY *dst_palette,
411     const D3DBOX *dst_box, const void *src_data, const D3DBOX *src_box, DWORD filter, D3DCOLOR color_key,
412     const D3DXIMAGE_INFO *src_info)
413 {
414     UINT row_pitch, slice_pitch;
415     const struct dds_header *header = src_data;
416     const BYTE *pixels = (BYTE *)(header + 1);
417
418     if (src_info->ResourceType != D3DRTYPE_VOLUMETEXTURE)
419         return D3DXERR_INVALIDDATA;
420
421     if (FAILED(calculate_dds_surface_size(src_info, src_info->Width, src_info->Height, &row_pitch, &slice_pitch)))
422         return E_NOTIMPL;
423
424     return D3DXLoadVolumeFromMemory(dst_volume, dst_palette, dst_box, pixels, src_info->Format,
425         row_pitch, slice_pitch, NULL, src_box, filter, color_key);
426 }
427
428 HRESULT load_texture_from_dds(IDirect3DTexture9 *texture, const void *src_data, const PALETTEENTRY *palette,
429     DWORD filter, D3DCOLOR color_key, const D3DXIMAGE_INFO *src_info)
430
431 {
432     HRESULT hr;
433     RECT src_rect;
434     UINT src_pitch;
435     UINT mip_level;
436     UINT mip_levels;
437     UINT mip_level_size;
438     UINT width, height;
439     IDirect3DSurface9 *surface;
440     const struct dds_header *header = src_data;
441     const BYTE *pixels = (BYTE *)(header + 1);
442
443     if (src_info->ResourceType != D3DRTYPE_TEXTURE)
444         return D3DXERR_INVALIDDATA;
445
446     width = src_info->Width;
447     height = src_info->Height;
448     mip_levels = min(src_info->MipLevels, IDirect3DTexture9_GetLevelCount(texture));
449     for (mip_level = 0; mip_level < mip_levels; mip_level++)
450     {
451         hr = calculate_dds_surface_size(src_info, width, height, &src_pitch, &mip_level_size);
452         if (FAILED(hr)) return hr;
453
454         SetRect(&src_rect, 0, 0, width, height);
455
456         IDirect3DTexture9_GetSurfaceLevel(texture, mip_level, &surface);
457         hr = D3DXLoadSurfaceFromMemory(surface, palette, NULL, pixels, src_info->Format, src_pitch,
458             NULL, &src_rect, filter, color_key);
459         IDirect3DSurface9_Release(surface);
460         if (FAILED(hr)) return hr;
461
462         pixels += mip_level_size;
463         width = max(1, width / 2);
464         height = max(1, height / 2);
465     }
466
467     return D3D_OK;
468 }
469
470 HRESULT load_cube_texture_from_dds(IDirect3DCubeTexture9 *cube_texture, const void *src_data,
471     const PALETTEENTRY *palette, DWORD filter, DWORD color_key, const D3DXIMAGE_INFO *src_info)
472 {
473     HRESULT hr;
474     int face;
475     int mip_level;
476     UINT size;
477     RECT src_rect;
478     UINT src_pitch;
479     UINT mip_levels;
480     UINT mip_level_size;
481     IDirect3DSurface9 *surface;
482     const struct dds_header *header = src_data;
483     const BYTE *pixels = (BYTE *)(header + 1);
484
485     if (src_info->ResourceType != D3DRTYPE_CUBETEXTURE)
486         return D3DXERR_INVALIDDATA;
487
488     if ((header->caps2 & DDS_CAPS2_CUBEMAP_ALL_FACES) != DDS_CAPS2_CUBEMAP_ALL_FACES)
489     {
490         WARN("Only full cubemaps are supported\n");
491         return D3DXERR_INVALIDDATA;
492     }
493
494     mip_levels = min(src_info->MipLevels, IDirect3DCubeTexture9_GetLevelCount(cube_texture));
495     for (face = D3DCUBEMAP_FACE_POSITIVE_X; face <= D3DCUBEMAP_FACE_NEGATIVE_Z; face++)
496     {
497         size = src_info->Width;
498         for (mip_level = 0; mip_level < src_info->MipLevels; mip_level++)
499         {
500             hr = calculate_dds_surface_size(src_info, size, size, &src_pitch, &mip_level_size);
501             if (FAILED(hr)) return hr;
502
503             /* if texture has fewer mip levels than DDS file, skip excessive mip levels */
504             if (mip_level < mip_levels)
505             {
506                 SetRect(&src_rect, 0, 0, size, size);
507
508                 IDirect3DCubeTexture9_GetCubeMapSurface(cube_texture, face, mip_level, &surface);
509                 hr = D3DXLoadSurfaceFromMemory(surface, palette, NULL, pixels, src_info->Format, src_pitch,
510                     NULL, &src_rect, filter, color_key);
511                 IDirect3DSurface9_Release(surface);
512                 if (FAILED(hr)) return hr;
513             }
514
515             pixels += mip_level_size;
516             size = max(1, size / 2);
517         }
518     }
519
520     return D3D_OK;
521 }
522
523 HRESULT load_volume_texture_from_dds(IDirect3DVolumeTexture9 *volume_texture, const void *src_data,
524     const PALETTEENTRY *palette, DWORD filter, DWORD color_key, const D3DXIMAGE_INFO *src_info)
525 {
526     HRESULT hr;
527     UINT mip_level;
528     UINT mip_levels;
529     UINT src_slice_pitch;
530     UINT src_row_pitch;
531     D3DBOX src_box;
532     UINT width, height, depth;
533     IDirect3DVolume9 *volume;
534     const struct dds_header *header = src_data;
535     const BYTE *pixels = (BYTE *)(header + 1);
536
537     if (src_info->ResourceType != D3DRTYPE_VOLUMETEXTURE)
538         return D3DXERR_INVALIDDATA;
539
540     width = src_info->Width;
541     height = src_info->Height;
542     depth = src_info->Depth;
543     mip_levels = min(src_info->MipLevels, IDirect3DVolumeTexture9_GetLevelCount(volume_texture));
544
545     for (mip_level = 0; mip_level < mip_levels; mip_level++)
546     {
547         hr = calculate_dds_surface_size(src_info, width, height, &src_row_pitch, &src_slice_pitch);
548         if (FAILED(hr)) return hr;
549
550         hr = IDirect3DVolumeTexture9_GetVolumeLevel(volume_texture, mip_level, &volume);
551         if (FAILED(hr)) return hr;
552
553         src_box.Left = 0;
554         src_box.Top = 0;
555         src_box.Right = width;
556         src_box.Bottom = height;
557         src_box.Front = 0;
558         src_box.Back = depth;
559
560         hr = D3DXLoadVolumeFromMemory(volume, palette, NULL, pixels, src_info->Format,
561             src_row_pitch, src_slice_pitch, NULL, &src_box, filter, color_key);
562
563         IDirect3DVolume9_Release(volume);
564         if (FAILED(hr)) return hr;
565
566         pixels += depth * src_slice_pitch;
567         width = max(1, width / 2);
568         height = max(1, height / 2);
569         depth = max(1, depth / 2);
570     }
571
572     return D3D_OK;
573 }
574
575 /************************************************************
576  * D3DXGetImageInfoFromFileInMemory
577  *
578  * Fills a D3DXIMAGE_INFO structure with info about an image
579  *
580  * PARAMS
581  *   data     [I] pointer to the image file data
582  *   datasize [I] size of the passed data
583  *   info     [O] pointer to the destination structure
584  *
585  * RETURNS
586  *   Success: D3D_OK, if info is not NULL and data and datasize make up a valid image file or
587  *                    if info is NULL and data and datasize are not NULL
588  *   Failure: D3DXERR_INVALIDDATA, if data is no valid image file and datasize and info are not NULL
589  *            D3DERR_INVALIDCALL, if data is NULL or
590  *                                if datasize is 0
591  *
592  * NOTES
593  *   datasize may be bigger than the actual file size
594  *
595  */
596 HRESULT WINAPI D3DXGetImageInfoFromFileInMemory(LPCVOID data, UINT datasize, D3DXIMAGE_INFO *info)
597 {
598     IWICImagingFactory *factory;
599     IWICBitmapDecoder *decoder = NULL;
600     IWICStream *stream;
601     HRESULT hr;
602     HRESULT initresult;
603
604     TRACE("(%p, %d, %p)\n", data, datasize, info);
605
606     if (!data || !datasize)
607         return D3DERR_INVALIDCALL;
608
609     if (!info)
610         return D3D_OK;
611
612     if ((datasize >= 4) && !strncmp(data, "DDS ", 4)) {
613         TRACE("File type is DDS\n");
614         return get_image_info_from_dds(data, datasize, info);
615     }
616
617     initresult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
618
619     hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, &IID_IWICImagingFactory, (void**)&factory);
620
621     if (SUCCEEDED(hr)) {
622         IWICImagingFactory_CreateStream(factory, &stream);
623         IWICStream_InitializeFromMemory(stream, (BYTE*)data, datasize);
624         hr = IWICImagingFactory_CreateDecoderFromStream(factory, (IStream*)stream, NULL, 0, &decoder);
625         IWICStream_Release(stream);
626         IWICImagingFactory_Release(factory);
627     }
628
629     if (FAILED(hr)) {
630         if ((datasize >= 2) && (!strncmp(data, "P3", 2) || !strncmp(data, "P6", 2)))
631             FIXME("File type PPM is not supported yet\n");
632         else if ((datasize >= 2) && !strncmp(data, "BM", 2))
633             FIXME("File type DIB is not supported yet\n");
634         else if ((datasize >= 10) && !strncmp(data, "#?RADIANCE", 10))
635             FIXME("File type HDR is not supported yet\n");
636         else if ((datasize >= 2) && (!strncmp(data, "PF", 2) || !strncmp(data, "Pf", 2)))
637             FIXME("File type PFM is not supported yet\n");
638     }
639
640     if (SUCCEEDED(hr)) {
641         GUID container_format;
642         UINT frame_count;
643
644         hr = IWICBitmapDecoder_GetContainerFormat(decoder, &container_format);
645         if (SUCCEEDED(hr)) {
646             if (IsEqualGUID(&container_format, &GUID_ContainerFormatBmp)) {
647                 TRACE("File type is BMP\n");
648                 info->ImageFileFormat = D3DXIFF_BMP;
649             } else if (IsEqualGUID(&container_format, &GUID_ContainerFormatPng)) {
650                 TRACE("File type is PNG\n");
651                 info->ImageFileFormat = D3DXIFF_PNG;
652             } else if(IsEqualGUID(&container_format, &GUID_ContainerFormatJpeg)) {
653                 TRACE("File type is JPG\n");
654                 info->ImageFileFormat = D3DXIFF_JPG;
655             } else if(IsEqualGUID(&container_format, &GUID_WineContainerFormatTga)) {
656                 TRACE("File type is TGA\n");
657                 info->ImageFileFormat = D3DXIFF_TGA;
658             } else {
659                 WARN("Unsupported image file format %s\n", debugstr_guid(&container_format));
660                 hr = D3DXERR_INVALIDDATA;
661             }
662         }
663
664         if (SUCCEEDED(hr))
665             hr = IWICBitmapDecoder_GetFrameCount(decoder, &frame_count);
666         if (SUCCEEDED(hr) && !frame_count)
667             hr = D3DXERR_INVALIDDATA;
668
669         if (SUCCEEDED(hr)) {
670             IWICBitmapFrameDecode *frame = NULL;
671
672             hr = IWICBitmapDecoder_GetFrame(decoder, 0, &frame);
673
674             if (SUCCEEDED(hr))
675                 hr = IWICBitmapFrameDecode_GetSize(frame, &info->Width, &info->Height);
676
677             if (SUCCEEDED(hr)) {
678                 WICPixelFormatGUID pixel_format;
679
680                 hr = IWICBitmapFrameDecode_GetPixelFormat(frame, &pixel_format);
681                 if (SUCCEEDED(hr)) {
682                     info->Format = wic_guid_to_d3dformat(&pixel_format);
683                     if (info->Format == D3DFMT_UNKNOWN) {
684                         WARN("Unsupported pixel format %s\n", debugstr_guid(&pixel_format));
685                         hr = D3DXERR_INVALIDDATA;
686                     }
687                 }
688             }
689
690             if (frame)
691                  IWICBitmapFrameDecode_Release(frame);
692
693             info->Depth = 1;
694             info->MipLevels = 1;
695             info->ResourceType = D3DRTYPE_TEXTURE;
696         }
697     }
698
699     if (decoder)
700         IWICBitmapDecoder_Release(decoder);
701
702     if (SUCCEEDED(initresult))
703         CoUninitialize();
704
705     if (FAILED(hr)) {
706         TRACE("Invalid or unsupported image file\n");
707         return D3DXERR_INVALIDDATA;
708     }
709
710     return D3D_OK;
711 }
712
713 /************************************************************
714  * D3DXGetImageInfoFromFile
715  *
716  * RETURNS
717  *   Success: D3D_OK, if we successfully load a valid image file or
718  *                    if we successfully load a file which is no valid image and info is NULL
719  *   Failure: D3DXERR_INVALIDDATA, if we fail to load file or
720  *                                 if file is not a valid image file and info is not NULL
721  *            D3DERR_INVALIDCALL, if file is NULL
722  *
723  */
724 HRESULT WINAPI D3DXGetImageInfoFromFileA(LPCSTR file, D3DXIMAGE_INFO *info)
725 {
726     LPWSTR widename;
727     HRESULT hr;
728     int strlength;
729
730     TRACE("(%s, %p): relay\n", debugstr_a(file), info);
731
732     if( !file ) return D3DERR_INVALIDCALL;
733
734     strlength = MultiByteToWideChar(CP_ACP, 0, file, -1, NULL, 0);
735     widename = HeapAlloc(GetProcessHeap(), 0, strlength * sizeof(*widename));
736     MultiByteToWideChar(CP_ACP, 0, file, -1, widename, strlength);
737
738     hr = D3DXGetImageInfoFromFileW(widename, info);
739     HeapFree(GetProcessHeap(), 0, widename);
740
741     return hr;
742 }
743
744 HRESULT WINAPI D3DXGetImageInfoFromFileW(LPCWSTR file, D3DXIMAGE_INFO *info)
745 {
746     HRESULT hr;
747     DWORD size;
748     LPVOID buffer;
749
750     TRACE("(%s, %p): relay\n", debugstr_w(file), info);
751
752     if( !file ) return D3DERR_INVALIDCALL;
753
754     hr = map_view_of_file(file, &buffer, &size);
755     if(FAILED(hr)) return D3DXERR_INVALIDDATA;
756
757     hr = D3DXGetImageInfoFromFileInMemory(buffer, size, info);
758     UnmapViewOfFile(buffer);
759
760     return hr;
761 }
762
763 /************************************************************
764  * D3DXGetImageInfoFromResource
765  *
766  * RETURNS
767  *   Success: D3D_OK, if resource is a valid image file
768  *   Failure: D3DXERR_INVALIDDATA, if resource is no valid image file or NULL or
769  *                                 if we fail to load resource
770  *
771  */
772 HRESULT WINAPI D3DXGetImageInfoFromResourceA(HMODULE module, LPCSTR resource, D3DXIMAGE_INFO *info)
773 {
774     HRSRC resinfo;
775
776     TRACE("(%p, %s, %p)\n", module, debugstr_a(resource), info);
777
778     resinfo = FindResourceA(module, resource, (LPCSTR)RT_RCDATA);
779     if(resinfo) {
780         LPVOID buffer;
781         HRESULT hr;
782         DWORD size;
783
784         hr = load_resource_into_memory(module, resinfo, &buffer, &size);
785         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
786         return D3DXGetImageInfoFromFileInMemory(buffer, size, info);
787     }
788
789     resinfo = FindResourceA(module, resource, (LPCSTR)RT_BITMAP);
790     if(resinfo) {
791         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
792         return E_NOTIMPL;
793     }
794     return D3DXERR_INVALIDDATA;
795 }
796
797 HRESULT WINAPI D3DXGetImageInfoFromResourceW(HMODULE module, LPCWSTR resource, D3DXIMAGE_INFO *info)
798 {
799     HRSRC resinfo;
800
801     TRACE("(%p, %s, %p)\n", module, debugstr_w(resource), info);
802
803     resinfo = FindResourceW(module, resource, (LPCWSTR)RT_RCDATA);
804     if(resinfo) {
805         LPVOID buffer;
806         HRESULT hr;
807         DWORD size;
808
809         hr = load_resource_into_memory(module, resinfo, &buffer, &size);
810         if(FAILED(hr)) return D3DXERR_INVALIDDATA;
811         return D3DXGetImageInfoFromFileInMemory(buffer, size, info);
812     }
813
814     resinfo = FindResourceW(module, resource, (LPCWSTR)RT_BITMAP);
815     if(resinfo) {
816         FIXME("Implement loading bitmaps from resource type RT_BITMAP\n");
817         return E_NOTIMPL;
818     }
819     return D3DXERR_INVALIDDATA;
820 }
821
822 /************************************************************
823  * D3DXLoadSurfaceFromFileInMemory
824  *
825  * Loads data from a given buffer into a surface and fills a given
826  * D3DXIMAGE_INFO structure with info about the source data.
827  *
828  * PARAMS
829  *   pDestSurface [I] pointer to the surface
830  *   pDestPalette [I] palette to use
831  *   pDestRect    [I] to be filled area of the surface
832  *   pSrcData     [I] pointer to the source data
833  *   SrcDataSize  [I] size of the source data in bytes
834  *   pSrcRect     [I] area of the source data to load
835  *   dwFilter     [I] filter to apply on stretching
836  *   Colorkey     [I] colorkey
837  *   pSrcInfo     [O] pointer to a D3DXIMAGE_INFO structure
838  *
839  * RETURNS
840  *   Success: D3D_OK
841  *   Failure: D3DERR_INVALIDCALL, if pDestSurface or pSrcData or SrcDataSize are NULL
842  *            D3DXERR_INVALIDDATA, if pSrcData is no valid image file
843  *
844  */
845 HRESULT WINAPI D3DXLoadSurfaceFromFileInMemory(IDirect3DSurface9 *pDestSurface,
846         const PALETTEENTRY *pDestPalette, const RECT *pDestRect, const void *pSrcData, UINT SrcDataSize,
847         const RECT *pSrcRect, DWORD dwFilter, D3DCOLOR Colorkey, D3DXIMAGE_INFO *pSrcInfo)
848 {
849     D3DXIMAGE_INFO imginfo;
850     HRESULT hr;
851
852     IWICImagingFactory *factory;
853     IWICBitmapDecoder *decoder;
854     IWICBitmapFrameDecode *bitmapframe;
855     IWICStream *stream;
856
857     const PixelFormatDesc *formatdesc;
858     WICRect wicrect;
859     RECT rect;
860
861     TRACE("dst_surface %p, dst_palette %p, dst_rect %s, src_data %p, src_data_size %u, "
862             "src_rect %s, filter %#x, color_key 0x%08x, src_info %p.\n",
863             pDestSurface, pDestPalette, wine_dbgstr_rect(pDestRect), pSrcData, SrcDataSize,
864             wine_dbgstr_rect(pSrcRect), dwFilter, Colorkey, pSrcInfo);
865
866     if (!pDestSurface || !pSrcData || !SrcDataSize)
867         return D3DERR_INVALIDCALL;
868
869     hr = D3DXGetImageInfoFromFileInMemory(pSrcData, SrcDataSize, &imginfo);
870
871     if (FAILED(hr))
872         return hr;
873
874     if (pSrcRect)
875     {
876         wicrect.X = pSrcRect->left;
877         wicrect.Y = pSrcRect->top;
878         wicrect.Width = pSrcRect->right - pSrcRect->left;
879         wicrect.Height = pSrcRect->bottom - pSrcRect->top;
880     }
881     else
882     {
883         wicrect.X = 0;
884         wicrect.Y = 0;
885         wicrect.Width = imginfo.Width;
886         wicrect.Height = imginfo.Height;
887     }
888
889     SetRect(&rect, 0, 0, wicrect.Width, wicrect.Height);
890
891     if (imginfo.ImageFileFormat == D3DXIFF_DDS)
892     {
893         hr = load_surface_from_dds(pDestSurface, pDestPalette, pDestRect, pSrcData, &rect,
894             dwFilter, Colorkey, &imginfo);
895         if (SUCCEEDED(hr) && pSrcInfo)
896             *pSrcInfo = imginfo;
897         return hr;
898     }
899
900     CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
901
902     if (FAILED(CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, &IID_IWICImagingFactory, (void**)&factory)))
903         goto cleanup_err;
904
905     if (FAILED(IWICImagingFactory_CreateStream(factory, &stream)))
906     {
907         IWICImagingFactory_Release(factory);
908         goto cleanup_err;
909     }
910
911     IWICStream_InitializeFromMemory(stream, (BYTE*)pSrcData, SrcDataSize);
912
913     hr = IWICImagingFactory_CreateDecoderFromStream(factory, (IStream*)stream, NULL, 0, &decoder);
914
915     IWICStream_Release(stream);
916     IWICImagingFactory_Release(factory);
917
918     if (FAILED(hr))
919         goto cleanup_err;
920
921     hr = IWICBitmapDecoder_GetFrame(decoder, 0, &bitmapframe);
922
923     if (FAILED(hr))
924         goto cleanup_bmp;
925
926     formatdesc = get_format_info(imginfo.Format);
927
928     if (formatdesc->format == D3DFMT_UNKNOWN)
929     {
930         FIXME("Unsupported pixel format\n");
931         hr = D3DXERR_INVALIDDATA;
932     }
933     else
934     {
935         BYTE *buffer;
936         DWORD pitch;
937
938         pitch = formatdesc->bytes_per_pixel * wicrect.Width;
939         buffer = HeapAlloc(GetProcessHeap(), 0, pitch * wicrect.Height);
940
941         hr = IWICBitmapFrameDecode_CopyPixels(bitmapframe, &wicrect, pitch,
942                                               pitch * wicrect.Height, buffer);
943
944         if (SUCCEEDED(hr))
945         {
946             hr = D3DXLoadSurfaceFromMemory(pDestSurface, pDestPalette, pDestRect,
947                                            buffer, imginfo.Format, pitch,
948                                            NULL, &rect, dwFilter, Colorkey);
949         }
950
951         HeapFree(GetProcessHeap(), 0, buffer);
952     }
953
954     IWICBitmapFrameDecode_Release(bitmapframe);
955
956 cleanup_bmp:
957     IWICBitmapDecoder_Release(decoder);
958
959 cleanup_err:
960     CoUninitialize();
961
962     if (FAILED(hr))
963         return D3DXERR_INVALIDDATA;
964
965     if (pSrcInfo)
966         *pSrcInfo = imginfo;
967
968     return D3D_OK;
969 }
970
971 HRESULT WINAPI D3DXLoadSurfaceFromFileA(IDirect3DSurface9 *dst_surface,
972         const PALETTEENTRY *dst_palette, const RECT *dst_rect, const char *src_file,
973         const RECT *src_rect, DWORD filter, D3DCOLOR color_key, D3DXIMAGE_INFO *src_info)
974 {
975     LPWSTR pWidename;
976     HRESULT hr;
977     int strlength;
978
979     TRACE("dst_surface %p, dst_palette %p, dst_rect %s, src_file %s, "
980             "src_rect %s, filter %#x, color_key 0x%08x, src_info %p.\n",
981             dst_surface, dst_palette, wine_dbgstr_rect(dst_rect), debugstr_a(src_file),
982             wine_dbgstr_rect(src_rect), filter, color_key, src_info);
983
984     if (!src_file || !dst_surface)
985         return D3DERR_INVALIDCALL;
986
987     strlength = MultiByteToWideChar(CP_ACP, 0, src_file, -1, NULL, 0);
988     pWidename = HeapAlloc(GetProcessHeap(), 0, strlength * sizeof(*pWidename));
989     MultiByteToWideChar(CP_ACP, 0, src_file, -1, pWidename, strlength);
990
991     hr = D3DXLoadSurfaceFromFileW(dst_surface, dst_palette, dst_rect,
992             pWidename, src_rect, filter, color_key, src_info);
993     HeapFree(GetProcessHeap(), 0, pWidename);
994
995     return hr;
996 }
997
998 HRESULT WINAPI D3DXLoadSurfaceFromFileW(IDirect3DSurface9 *dst_surface,
999         const PALETTEENTRY *dst_palette, const RECT *dst_rect, const WCHAR *src_file,
1000         const RECT *src_rect, DWORD filter, D3DCOLOR color_key, D3DXIMAGE_INFO *src_info)
1001 {
1002     UINT data_size;
1003     void *data;
1004     HRESULT hr;
1005
1006     TRACE("dst_surface %p, dst_palette %p, dst_rect %s, src_file %s, "
1007             "src_rect %s, filter %#x, color_key 0x%08x, src_info %p.\n",
1008             dst_surface, dst_palette, wine_dbgstr_rect(dst_rect), debugstr_w(src_file),
1009             wine_dbgstr_rect(src_rect), filter, color_key, src_info);
1010
1011     if (!src_file || !dst_surface)
1012         return D3DERR_INVALIDCALL;
1013
1014     if (FAILED(map_view_of_file(src_file, &data, &data_size)))
1015         return D3DXERR_INVALIDDATA;
1016
1017     hr = D3DXLoadSurfaceFromFileInMemory(dst_surface, dst_palette, dst_rect,
1018             data, data_size, src_rect, filter, color_key, src_info);
1019     UnmapViewOfFile(data);
1020
1021     return hr;
1022 }
1023
1024 HRESULT WINAPI D3DXLoadSurfaceFromResourceA(IDirect3DSurface9 *dst_surface,
1025         const PALETTEENTRY *dst_palette, const RECT *dst_rect, HMODULE src_module, const char *resource,
1026         const RECT *src_rect, DWORD filter, D3DCOLOR color_key, D3DXIMAGE_INFO *src_info)
1027 {
1028     HRSRC hResInfo;
1029
1030     TRACE("dst_surface %p, dst_palette %p, dst_rect %s, src_module %p, resource %s, "
1031             "src_rect %s, filter %#x, color_key 0x%08x, src_info %p.\n",
1032             dst_surface, dst_palette, wine_dbgstr_rect(dst_rect), src_module, debugstr_a(resource),
1033             wine_dbgstr_rect(src_rect), filter, color_key, src_info);
1034
1035     if (!dst_surface)
1036         return D3DERR_INVALIDCALL;
1037
1038     if ((hResInfo = FindResourceA(src_module, resource, (const char *)RT_RCDATA)))
1039     {
1040         UINT data_size;
1041         void *data;
1042
1043         if (FAILED(load_resource_into_memory(src_module, hResInfo, &data, &data_size)))
1044             return D3DXERR_INVALIDDATA;
1045
1046         return D3DXLoadSurfaceFromFileInMemory(dst_surface, dst_palette, dst_rect,
1047                 data, data_size, src_rect, filter, color_key, src_info);
1048     }
1049
1050     if ((hResInfo = FindResourceA(src_module, resource, (const char *)RT_BITMAP)))
1051     {
1052         FIXME("Implement loading bitmaps from resource type RT_BITMAP.\n");
1053         return E_NOTIMPL;
1054     }
1055
1056     return D3DXERR_INVALIDDATA;
1057 }
1058
1059 HRESULT WINAPI D3DXLoadSurfaceFromResourceW(IDirect3DSurface9 *dst_surface,
1060         const PALETTEENTRY *dst_palette, const RECT *dst_rect, HMODULE src_module, const WCHAR *resource,
1061         const RECT *src_rect, DWORD filter, D3DCOLOR color_key, D3DXIMAGE_INFO *src_info)
1062 {
1063     HRSRC hResInfo;
1064
1065     TRACE("dst_surface %p, dst_palette %p, dst_rect %s, src_module %p, resource %s, "
1066             "src_rect %s, filter %#x, color_key 0x%08x, src_info %p.\n",
1067             dst_surface, dst_palette, wine_dbgstr_rect(dst_rect), src_module, debugstr_w(resource),
1068             wine_dbgstr_rect(src_rect), filter, color_key, src_info);
1069
1070     if (!dst_surface)
1071         return D3DERR_INVALIDCALL;
1072
1073     if ((hResInfo = FindResourceW(src_module, resource, (const WCHAR *)RT_RCDATA)))
1074     {
1075         UINT data_size;
1076         void *data;
1077
1078         if (FAILED(load_resource_into_memory(src_module, hResInfo, &data, &data_size)))
1079             return D3DXERR_INVALIDDATA;
1080
1081         return D3DXLoadSurfaceFromFileInMemory(dst_surface, dst_palette, dst_rect,
1082                 data, data_size, src_rect, filter, color_key, src_info);
1083     }
1084
1085     if ((hResInfo = FindResourceW(src_module, resource, (const WCHAR *)RT_BITMAP)))
1086     {
1087         FIXME("Implement loading bitmaps from resource type RT_BITMAP.\n");
1088         return E_NOTIMPL;
1089     }
1090
1091     return D3DXERR_INVALIDDATA;
1092 }
1093
1094
1095 /************************************************************
1096  * helper functions for D3DXLoadSurfaceFromMemory
1097  */
1098 struct argb_conversion_info
1099 {
1100     CONST PixelFormatDesc *srcformat;
1101     CONST PixelFormatDesc *destformat;
1102     DWORD srcshift[4], destshift[4];
1103     DWORD srcmask[4], destmask[4];
1104     BOOL process_channel[4];
1105     DWORD channelmask;
1106 };
1107
1108 static void init_argb_conversion_info(CONST PixelFormatDesc *srcformat, CONST PixelFormatDesc *destformat, struct argb_conversion_info *info)
1109 {
1110     UINT i;
1111     ZeroMemory(info->process_channel, 4 * sizeof(BOOL));
1112     info->channelmask = 0;
1113
1114     info->srcformat  =  srcformat;
1115     info->destformat = destformat;
1116
1117     for(i = 0;i < 4;i++) {
1118         /* srcshift is used to extract the _relevant_ components */
1119         info->srcshift[i]  =  srcformat->shift[i] + max( srcformat->bits[i] - destformat->bits[i], 0);
1120
1121         /* destshift is used to move the components to the correct position */
1122         info->destshift[i] = destformat->shift[i] + max(destformat->bits[i] -  srcformat->bits[i], 0);
1123
1124         info->srcmask[i]  = ((1 <<  srcformat->bits[i]) - 1) <<  srcformat->shift[i];
1125         info->destmask[i] = ((1 << destformat->bits[i]) - 1) << destformat->shift[i];
1126
1127         /* channelmask specifies bits which aren't used in the source format but in the destination one */
1128         if(destformat->bits[i]) {
1129             if(srcformat->bits[i]) info->process_channel[i] = TRUE;
1130             else info->channelmask |= info->destmask[i];
1131         }
1132     }
1133 }
1134
1135 static DWORD dword_from_bytes(CONST BYTE *src, UINT bytes_per_pixel)
1136 {
1137     DWORD ret = 0;
1138     static BOOL fixme_once;
1139
1140     if(bytes_per_pixel > sizeof(DWORD)) {
1141         if(!fixme_once++) FIXME("Unsupported image: %u bytes per pixel\n", bytes_per_pixel);
1142         bytes_per_pixel = sizeof(DWORD);
1143     }
1144
1145     memcpy(&ret, src, bytes_per_pixel);
1146     return ret;
1147 }
1148
1149 static void dword_to_bytes(BYTE *dst, DWORD dword, UINT bytes_per_pixel)
1150 {
1151     static BOOL fixme_once;
1152
1153     if(bytes_per_pixel > sizeof(DWORD)) {
1154         if(!fixme_once++) FIXME("Unsupported image: %u bytes per pixel\n", bytes_per_pixel);
1155         ZeroMemory(dst, bytes_per_pixel);
1156         bytes_per_pixel = sizeof(DWORD);
1157     }
1158
1159     memcpy(dst, &dword, bytes_per_pixel);
1160 }
1161
1162 /************************************************************
1163  * get_relevant_argb_components
1164  *
1165  * Extracts the relevant components from the source color and
1166  * drops the less significant bits if they aren't used by the destination format.
1167  */
1168 static void get_relevant_argb_components(CONST struct argb_conversion_info *info, CONST DWORD col, DWORD *out)
1169 {
1170     UINT i = 0;
1171     for(;i < 4;i++)
1172         if(info->process_channel[i])
1173             out[i] = (col & info->srcmask[i]) >> info->srcshift[i];
1174 }
1175
1176 /************************************************************
1177  * make_argb_color
1178  *
1179  * Recombines the output of get_relevant_argb_components and converts
1180  * it to the destination format.
1181  */
1182 static DWORD make_argb_color(CONST struct argb_conversion_info *info, CONST DWORD *in)
1183 {
1184     UINT i;
1185     DWORD val = 0;
1186
1187     for(i = 0;i < 4;i++) {
1188         if(info->process_channel[i]) {
1189             /* necessary to make sure that e.g. an X4R4G4B4 white maps to an R8G8B8 white instead of 0xf0f0f0 */
1190             signed int shift;
1191             for(shift = info->destshift[i]; shift > info->destformat->shift[i]; shift -= info->srcformat->bits[i]) val |= in[i] << shift;
1192             val |= (in[i] >> (info->destformat->shift[i] - shift)) << info->destformat->shift[i];
1193         }
1194     }
1195     val |= info->channelmask;   /* new channels are set to their maximal value */
1196     return val;
1197 }
1198
1199 static void format_to_vec4(const PixelFormatDesc *format, const DWORD *src, struct vec4 *dst)
1200 {
1201     DWORD mask;
1202
1203     if (format->bits[1])
1204     {
1205         mask = (1 << format->bits[1]) - 1;
1206         dst->x = (float)((*src >> format->shift[1]) & mask) / mask;
1207     }
1208     else
1209         dst->x = 1.0f;
1210
1211     if (format->bits[2])
1212     {
1213         mask = (1 << format->bits[2]) - 1;
1214         dst->y = (float)((*src >> format->shift[2]) & mask) / mask;
1215     }
1216     else
1217         dst->y = 1.0f;
1218
1219     if (format->bits[3])
1220     {
1221         mask = (1 << format->bits[3]) - 1;
1222         dst->z = (float)((*src >> format->shift[3]) & mask) / mask;
1223     }
1224     else
1225         dst->z = 1.0f;
1226
1227     if (format->bits[0])
1228     {
1229         mask = (1 << format->bits[0]) - 1;
1230         dst->w = (float)((*src >> format->shift[0]) & mask) / mask;
1231     }
1232     else
1233         dst->w = 1.0f;
1234 }
1235
1236 static void format_from_vec4(const PixelFormatDesc *format, const struct vec4 *src, DWORD *dst)
1237 {
1238     *dst = 0;
1239
1240     if (format->bits[1])
1241         *dst |= (DWORD)(src->x * ((1 << format->bits[1]) - 1) + 0.5f) << format->shift[1];
1242     if (format->bits[2])
1243         *dst |= (DWORD)(src->y * ((1 << format->bits[2]) - 1) + 0.5f) << format->shift[2];
1244     if (format->bits[3])
1245         *dst |= (DWORD)(src->z * ((1 << format->bits[3]) - 1) + 0.5f) << format->shift[3];
1246     if (format->bits[0])
1247         *dst |= (DWORD)(src->w * ((1 << format->bits[0]) - 1) + 0.5f) << format->shift[0];
1248 }
1249
1250 /************************************************************
1251  * copy_simple_data
1252  *
1253  * Copies the source buffer to the destination buffer, performing
1254  * any necessary format conversion and color keying.
1255  * Pixels outsize the source rect are blacked out.
1256  * Works only for ARGB formats with 1 - 4 bytes per pixel.
1257  */
1258 void copy_simple_data(const BYTE *src, UINT src_row_pitch, UINT src_slice_pitch, struct volume *src_size, const PixelFormatDesc *src_format,
1259         BYTE *dst, UINT dst_row_pitch, UINT dst_slice_pitch, struct volume *dst_size, const PixelFormatDesc *dst_format, D3DCOLOR color_key)
1260 {
1261     struct argb_conversion_info conv_info, ck_conv_info;
1262     const PixelFormatDesc *ck_format = NULL;
1263     DWORD channels[4], pixel;
1264     UINT min_width, min_height, min_depth;
1265     UINT x, y, z;
1266
1267     ZeroMemory(channels, sizeof(channels));
1268     init_argb_conversion_info(src_format, dst_format, &conv_info);
1269
1270     min_width = min(src_size->width, dst_size->width);
1271     min_height = min(src_size->height, dst_size->height);
1272     min_depth = min(src_size->depth, dst_size->depth);
1273
1274     if (color_key)
1275     {
1276         /* Color keys are always represented in D3DFMT_A8R8G8B8 format. */
1277         ck_format = get_format_info(D3DFMT_A8R8G8B8);
1278         init_argb_conversion_info(src_format, ck_format, &ck_conv_info);
1279     }
1280
1281     for (z = 0; z < min_depth; z++) {
1282         const BYTE *src_slice_ptr = src + z * src_slice_pitch;
1283         BYTE *dst_slice_ptr = dst + z * dst_slice_pitch;
1284
1285         for (y = 0; y < min_height; y++) {
1286             const BYTE *src_ptr = src_slice_ptr + y * src_row_pitch;
1287             BYTE *dst_ptr = dst_slice_ptr + y * dst_row_pitch;
1288             DWORD val;
1289
1290             for (x = 0; x < min_width; x++) {
1291                 /* extract source color components */
1292                 pixel = dword_from_bytes(src_ptr, src_format->bytes_per_pixel);
1293
1294                 if (!src_format->to_rgba && !dst_format->from_rgba)
1295                 {
1296                     get_relevant_argb_components(&conv_info, pixel, channels);
1297                     val = make_argb_color(&conv_info, channels);
1298
1299                     if (color_key)
1300                     {
1301                         get_relevant_argb_components(&ck_conv_info, pixel, channels);
1302                         pixel = make_argb_color(&ck_conv_info, channels);
1303                         if (pixel == color_key)
1304                             val &= ~conv_info.destmask[0];
1305                     }
1306                 }
1307                 else
1308                 {
1309                     struct vec4 color, tmp;
1310
1311                     format_to_vec4(src_format, &pixel, &color);
1312                     if (src_format->to_rgba)
1313                         src_format->to_rgba(&color, &tmp);
1314                     else
1315                         tmp = color;
1316
1317                     if (ck_format)
1318                     {
1319                         format_from_vec4(ck_format, &tmp, &pixel);
1320                         if (pixel == color_key)
1321                             tmp.w = 0.0f;
1322                     }
1323
1324                     if (dst_format->from_rgba)
1325                         dst_format->from_rgba(&tmp, &color);
1326                     else
1327                         color = tmp;
1328
1329                     format_from_vec4(dst_format, &color, &val);
1330                 }
1331
1332                 dword_to_bytes(dst_ptr, val, dst_format->bytes_per_pixel);
1333                 src_ptr  +=  src_format->bytes_per_pixel;
1334                 dst_ptr += dst_format->bytes_per_pixel;
1335             }
1336
1337             if (src_size->width < dst_size->width) /* black out remaining pixels */
1338                 memset(dst_ptr, 0, dst_format->bytes_per_pixel * (dst_size->width - src_size->width));
1339         }
1340
1341         if (src_size->height < dst_size->height) /* black out remaining pixels */
1342             memset(dst + src_size->height * dst_row_pitch, 0, dst_row_pitch * (dst_size->height - src_size->height));
1343     }
1344     if (src_size->depth < dst_size->depth) /* black out remaining pixels */
1345         memset(dst + src_size->depth * dst_slice_pitch, 0, dst_slice_pitch * (dst_size->depth - src_size->depth));
1346 }
1347
1348 /************************************************************
1349  * point_filter_simple_data
1350  *
1351  * Copies the source buffer to the destination buffer, performing
1352  * any necessary format conversion, color keying and stretching
1353  * using a point filter.
1354  * Works only for ARGB formats with 1 - 4 bytes per pixel.
1355  */
1356 void point_filter_simple_data(const BYTE *src, UINT src_row_pitch, UINT src_slice_pitch, struct volume *src_size, const PixelFormatDesc *src_format,
1357         BYTE *dst, UINT dst_row_pitch, UINT dst_slice_pitch, struct volume *dst_size, const PixelFormatDesc *dst_format, D3DCOLOR color_key)
1358 {
1359     struct argb_conversion_info conv_info, ck_conv_info;
1360     const PixelFormatDesc *ck_format = NULL;
1361     DWORD channels[4], pixel;
1362     UINT x, y, z;
1363
1364     ZeroMemory(channels, sizeof(channels));
1365     init_argb_conversion_info(src_format, dst_format, &conv_info);
1366
1367     if (color_key)
1368     {
1369         /* Color keys are always represented in D3DFMT_A8R8G8B8 format. */
1370         ck_format = get_format_info(D3DFMT_A8R8G8B8);
1371         init_argb_conversion_info(src_format, ck_format, &ck_conv_info);
1372     }
1373
1374     for (z = 0; z < dst_size->depth; z++)
1375     {
1376         BYTE *dst_slice_ptr = dst + z * dst_slice_pitch;
1377         const BYTE *src_slice_ptr = src + src_slice_pitch * (z * src_size->depth / dst_size->depth);
1378
1379         for (y = 0; y < dst_size->height; y++)
1380         {
1381             BYTE *dst_ptr = dst_slice_ptr + y * dst_row_pitch;
1382             const BYTE *src_row_ptr = src_slice_ptr + src_row_pitch * (y * src_size->height / dst_size->height);
1383
1384             for (x = 0; x < dst_size->width; x++)
1385             {
1386                 const BYTE *src_ptr = src_row_ptr + (x * src_size->width / dst_size->width) * src_format->bytes_per_pixel;
1387                 DWORD val;
1388
1389                 /* extract source color components */
1390                 pixel = dword_from_bytes(src_ptr, src_format->bytes_per_pixel);
1391
1392                 if (!src_format->to_rgba && !dst_format->from_rgba)
1393                 {
1394                     get_relevant_argb_components(&conv_info, pixel, channels);
1395                     val = make_argb_color(&conv_info, channels);
1396
1397                     if (color_key)
1398                     {
1399                         get_relevant_argb_components(&ck_conv_info, pixel, channels);
1400                         pixel = make_argb_color(&ck_conv_info, channels);
1401                         if (pixel == color_key)
1402                             val &= ~conv_info.destmask[0];
1403                     }
1404                 }
1405                 else
1406                 {
1407                     struct vec4 color, tmp;
1408
1409                     format_to_vec4(src_format, &pixel, &color);
1410                     if (src_format->to_rgba)
1411                         src_format->to_rgba(&color, &tmp);
1412                     else
1413                         tmp = color;
1414
1415                     if (ck_format)
1416                     {
1417                         format_from_vec4(ck_format, &tmp, &pixel);
1418                         if (pixel == color_key)
1419                             tmp.w = 0.0f;
1420                     }
1421
1422                     if (dst_format->from_rgba)
1423                         dst_format->from_rgba(&tmp, &color);
1424                     else
1425                         color = tmp;
1426
1427                     format_from_vec4(dst_format, &color, &val);
1428                 }
1429
1430                 dword_to_bytes(dst_ptr, val, dst_format->bytes_per_pixel);
1431                 dst_ptr += dst_format->bytes_per_pixel;
1432             }
1433         }
1434     }
1435 }
1436
1437 /************************************************************
1438  * D3DXLoadSurfaceFromMemory
1439  *
1440  * Loads data from a given memory chunk into a surface,
1441  * applying any of the specified filters.
1442  *
1443  * PARAMS
1444  *   pDestSurface [I] pointer to the surface
1445  *   pDestPalette [I] palette to use
1446  *   pDestRect    [I] to be filled area of the surface
1447  *   pSrcMemory   [I] pointer to the source data
1448  *   SrcFormat    [I] format of the source pixel data
1449  *   SrcPitch     [I] number of bytes in a row
1450  *   pSrcPalette  [I] palette used in the source image
1451  *   pSrcRect     [I] area of the source data to load
1452  *   dwFilter     [I] filter to apply on stretching
1453  *   Colorkey     [I] colorkey
1454  *
1455  * RETURNS
1456  *   Success: D3D_OK, if we successfully load the pixel data into our surface or
1457  *                    if pSrcMemory is NULL but the other parameters are valid
1458  *   Failure: D3DERR_INVALIDCALL, if pDestSurface, SrcPitch or pSrcRect are NULL or
1459  *                                if SrcFormat is an invalid format (other than D3DFMT_UNKNOWN) or
1460  *                                if DestRect is invalid
1461  *            D3DXERR_INVALIDDATA, if we fail to lock pDestSurface
1462  *            E_FAIL, if SrcFormat is D3DFMT_UNKNOWN or the dimensions of pSrcRect are invalid
1463  *
1464  * NOTES
1465  *   pSrcRect specifies the dimensions of the source data;
1466  *   negative values for pSrcRect are allowed as we're only looking at the width and height anyway.
1467  *
1468  */
1469 HRESULT WINAPI D3DXLoadSurfaceFromMemory(IDirect3DSurface9 *dst_surface,
1470         const PALETTEENTRY *dst_palette, const RECT *dst_rect, const void *src_memory,
1471         D3DFORMAT src_format, UINT src_pitch, const PALETTEENTRY *src_palette, const RECT *src_rect,
1472         DWORD filter, D3DCOLOR color_key)
1473 {
1474     CONST PixelFormatDesc *srcformatdesc, *destformatdesc;
1475     D3DSURFACE_DESC surfdesc;
1476     D3DLOCKED_RECT lockrect;
1477     struct volume src_size, dst_size;
1478     HRESULT hr;
1479
1480     TRACE("(%p, %p, %s, %p, %#x, %u, %p, %s %#x, 0x%08x)\n",
1481             dst_surface, dst_palette, wine_dbgstr_rect(dst_rect), src_memory, src_format,
1482             src_pitch, src_palette, wine_dbgstr_rect(src_rect), filter, color_key);
1483
1484     if (!dst_surface || !src_memory || !src_rect)
1485     {
1486         WARN("Invalid argument specified.\n");
1487         return D3DERR_INVALIDCALL;
1488     }
1489     if (src_format == D3DFMT_UNKNOWN
1490             || src_rect->left >= src_rect->right
1491             || src_rect->top >= src_rect->bottom)
1492     {
1493         WARN("Invalid src_format or src_rect.\n");
1494         return E_FAIL;
1495     }
1496
1497     if (filter == D3DX_DEFAULT)
1498         filter = D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER;
1499
1500     IDirect3DSurface9_GetDesc(dst_surface, &surfdesc);
1501
1502     src_size.width = src_rect->right - src_rect->left;
1503     src_size.height = src_rect->bottom - src_rect->top;
1504     src_size.depth = 1;
1505     if (!dst_rect)
1506     {
1507         dst_size.width = surfdesc.Width;
1508         dst_size.height = surfdesc.Height;
1509     }
1510     else
1511     {
1512         if (dst_rect->left > dst_rect->right || dst_rect->right > surfdesc.Width
1513                 || dst_rect->top > dst_rect->bottom || dst_rect->bottom > surfdesc.Height
1514                 || dst_rect->left < 0 || dst_rect->top < 0)
1515         {
1516             WARN("Invalid dst_rect specified.\n");
1517             return D3DERR_INVALIDCALL;
1518         }
1519         dst_size.width = dst_rect->right - dst_rect->left;
1520         dst_size.height = dst_rect->bottom - dst_rect->top;
1521         if (!dst_size.width || !dst_size.height)
1522             return D3D_OK;
1523     }
1524     dst_size.depth = 1;
1525
1526     srcformatdesc = get_format_info(src_format);
1527     destformatdesc = get_format_info(surfdesc.Format);
1528     if (srcformatdesc->type == FORMAT_UNKNOWN || destformatdesc->type == FORMAT_UNKNOWN)
1529     {
1530         FIXME("Unsupported pixel format conversion %#x -> %#x\n", src_format, surfdesc.Format);
1531         return E_NOTIMPL;
1532     }
1533
1534     if (src_format == surfdesc.Format
1535             && dst_size.width == src_size.width
1536             && dst_size.height == src_size.height) /* Simple copy. */
1537     {
1538         UINT row_block_count = ((src_size.width + srcformatdesc->block_width - 1) / srcformatdesc->block_width);
1539         UINT row_count = (src_size.height + srcformatdesc->block_height - 1) / srcformatdesc->block_height;
1540         const BYTE *src_addr;
1541         BYTE *dst_addr;
1542         UINT row;
1543
1544         if (src_rect->left & (srcformatdesc->block_width - 1)
1545                 || src_rect->top & (srcformatdesc->block_height - 1)
1546                 || (src_rect->right & (srcformatdesc->block_width - 1)
1547                     && src_size.width != surfdesc.Width)
1548                 || (src_rect->bottom & (srcformatdesc->block_height - 1)
1549                     && src_size.height != surfdesc.Height))
1550         {
1551             WARN("Source rect %s is misaligned.\n", wine_dbgstr_rect(src_rect));
1552             return D3DXERR_INVALIDDATA;
1553         }
1554
1555         if (FAILED(hr = IDirect3DSurface9_LockRect(dst_surface, &lockrect, dst_rect, 0)))
1556             return D3DXERR_INVALIDDATA;
1557
1558         src_addr = src_memory;
1559         src_addr += (src_rect->top / srcformatdesc->block_height) * src_pitch;
1560         src_addr += (src_rect->left / srcformatdesc->block_width) * srcformatdesc->block_byte_count;
1561         dst_addr = lockrect.pBits;
1562
1563         for (row = 0; row < row_count; ++row)
1564         {
1565             memcpy(dst_addr, src_addr, row_block_count * srcformatdesc->block_byte_count);
1566             src_addr += src_pitch;
1567             dst_addr += lockrect.Pitch;
1568         }
1569
1570         IDirect3DSurface9_UnlockRect(dst_surface);
1571     }
1572     else /* Stretching or format conversion. */
1573     {
1574         if (srcformatdesc->bytes_per_pixel > 4 || destformatdesc->bytes_per_pixel > 4
1575                 || srcformatdesc->block_height != 1 || srcformatdesc->block_width != 1
1576                 || destformatdesc->block_height != 1 || destformatdesc->block_width != 1)
1577         {
1578             FIXME("Format conversion missing %#x -> %#x\n", src_format, surfdesc.Format);
1579             return E_NOTIMPL;
1580         }
1581
1582         if (FAILED(hr = IDirect3DSurface9_LockRect(dst_surface, &lockrect, dst_rect, 0)))
1583             return D3DXERR_INVALIDDATA;
1584
1585         if ((filter & 0xf) == D3DX_FILTER_NONE)
1586         {
1587             copy_simple_data(src_memory, src_pitch, 0, &src_size, srcformatdesc,
1588                     lockrect.pBits, lockrect.Pitch, 0, &dst_size, destformatdesc, color_key);
1589         }
1590         else /* if ((filter & 0xf) == D3DX_FILTER_POINT) */
1591         {
1592             if ((filter & 0xf) != D3DX_FILTER_POINT)
1593                 FIXME("Unhandled filter %#x.\n", filter);
1594
1595             /* Always apply a point filter until D3DX_FILTER_LINEAR,
1596              * D3DX_FILTER_TRIANGLE and D3DX_FILTER_BOX are implemented. */
1597             point_filter_simple_data(src_memory, src_pitch, 0, &src_size, srcformatdesc,
1598                     lockrect.pBits, lockrect.Pitch, 0, &dst_size, destformatdesc, color_key);
1599         }
1600
1601         IDirect3DSurface9_UnlockRect(dst_surface);
1602     }
1603
1604     return D3D_OK;
1605 }
1606
1607 /************************************************************
1608  * D3DXLoadSurfaceFromSurface
1609  *
1610  * Copies the contents from one surface to another, performing any required
1611  * format conversion, resizing or filtering.
1612  *
1613  * PARAMS
1614  *   pDestSurface [I] pointer to the destination surface
1615  *   pDestPalette [I] palette to use
1616  *   pDestRect    [I] to be filled area of the surface
1617  *   pSrcSurface  [I] pointer to the source surface
1618  *   pSrcPalette  [I] palette used for the source surface
1619  *   pSrcRect     [I] area of the source data to load
1620  *   dwFilter     [I] filter to apply on resizing
1621  *   Colorkey     [I] any ARGB value or 0 to disable color-keying
1622  *
1623  * RETURNS
1624  *   Success: D3D_OK
1625  *   Failure: D3DERR_INVALIDCALL, if pDestSurface or pSrcSurface are NULL
1626  *            D3DXERR_INVALIDDATA, if one of the surfaces is not lockable
1627  *
1628  */
1629 HRESULT WINAPI D3DXLoadSurfaceFromSurface(IDirect3DSurface9 *dst_surface,
1630         const PALETTEENTRY *dst_palette, const RECT *dst_rect, IDirect3DSurface9 *src_surface,
1631         const PALETTEENTRY *src_palette, const RECT *src_rect, DWORD filter, D3DCOLOR color_key)
1632 {
1633     RECT rect;
1634     D3DLOCKED_RECT lock;
1635     D3DSURFACE_DESC SrcDesc;
1636     HRESULT hr;
1637
1638     TRACE("dst_surface %p, dst_palette %p, dst_rect %s, src_surface %p, "
1639             "src_palette %p, src_rect %s, filter %#x, color_key 0x%08x.\n",
1640             dst_surface, dst_palette, wine_dbgstr_rect(dst_rect), src_surface,
1641             src_palette, wine_dbgstr_rect(src_rect), filter, color_key);
1642
1643     if (!dst_surface || !src_surface)
1644         return D3DERR_INVALIDCALL;
1645
1646     IDirect3DSurface9_GetDesc(src_surface, &SrcDesc);
1647
1648     if (!src_rect)
1649         SetRect(&rect, 0, 0, SrcDesc.Width, SrcDesc.Height);
1650     else
1651         rect = *src_rect;
1652
1653     if (FAILED(IDirect3DSurface9_LockRect(src_surface, &lock, NULL, D3DLOCK_READONLY)))
1654         return D3DXERR_INVALIDDATA;
1655
1656     hr = D3DXLoadSurfaceFromMemory(dst_surface, dst_palette, dst_rect,
1657             lock.pBits, SrcDesc.Format, lock.Pitch, src_palette, &rect, filter, color_key);
1658
1659     IDirect3DSurface9_UnlockRect(src_surface);
1660
1661     return hr;
1662 }
1663
1664
1665 HRESULT WINAPI D3DXSaveSurfaceToFileA(const char *dst_filename, D3DXIMAGE_FILEFORMAT file_format,
1666         IDirect3DSurface9 *src_surface, const PALETTEENTRY *src_palette, const RECT *src_rect)
1667 {
1668     int len;
1669     WCHAR *filename;
1670     HRESULT hr;
1671     ID3DXBuffer *buffer;
1672
1673     TRACE("(%s, %#x, %p, %p, %s): relay\n",
1674             wine_dbgstr_a(dst_filename), file_format, src_surface, src_palette, wine_dbgstr_rect(src_rect));
1675
1676     if (!dst_filename) return D3DERR_INVALIDCALL;
1677
1678     len = MultiByteToWideChar(CP_ACP, 0, dst_filename, -1, NULL, 0);
1679     filename = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1680     if (!filename) return E_OUTOFMEMORY;
1681     MultiByteToWideChar(CP_ACP, 0, dst_filename, -1, filename, len);
1682
1683     hr = D3DXSaveSurfaceToFileInMemory(&buffer, file_format, src_surface, src_palette, src_rect);
1684     if (SUCCEEDED(hr))
1685     {
1686         hr = write_buffer_to_file(filename, buffer);
1687         ID3DXBuffer_Release(buffer);
1688     }
1689
1690     HeapFree(GetProcessHeap(), 0, filename);
1691     return hr;
1692 }
1693
1694 HRESULT WINAPI D3DXSaveSurfaceToFileW(const WCHAR *dst_filename, D3DXIMAGE_FILEFORMAT file_format,
1695         IDirect3DSurface9 *src_surface, const PALETTEENTRY *src_palette, const RECT *src_rect)
1696 {
1697     HRESULT hr;
1698     ID3DXBuffer *buffer;
1699
1700     TRACE("(%s, %#x, %p, %p, %s): relay\n",
1701         wine_dbgstr_w(dst_filename), file_format, src_surface, src_palette, wine_dbgstr_rect(src_rect));
1702
1703     if (!dst_filename) return D3DERR_INVALIDCALL;
1704
1705     hr = D3DXSaveSurfaceToFileInMemory(&buffer, file_format, src_surface, src_palette, src_rect);
1706     if (SUCCEEDED(hr))
1707     {
1708         hr = write_buffer_to_file(dst_filename, buffer);
1709         ID3DXBuffer_Release(buffer);
1710     }
1711
1712     return hr;
1713 }
1714
1715 HRESULT WINAPI D3DXSaveSurfaceToFileInMemory(ID3DXBuffer **dst_buffer, D3DXIMAGE_FILEFORMAT file_format,
1716         IDirect3DSurface9 *src_surface, const PALETTEENTRY *src_palette, const RECT *src_rect)
1717 {
1718     IWICBitmapEncoder *encoder = NULL;
1719     IWICBitmapFrameEncode *frame = NULL;
1720     IPropertyBag2 *encoder_options = NULL;
1721     IStream *stream = NULL;
1722     HRESULT hr;
1723     HRESULT initresult;
1724     const CLSID *encoder_clsid;
1725     const GUID *pixel_format_guid;
1726     WICPixelFormatGUID wic_pixel_format;
1727     D3DFORMAT d3d_pixel_format;
1728     D3DSURFACE_DESC src_surface_desc;
1729     D3DLOCKED_RECT locked_rect;
1730     int width, height;
1731     STATSTG stream_stats;
1732     HGLOBAL stream_hglobal;
1733     ID3DXBuffer *buffer;
1734     DWORD size;
1735
1736     TRACE("(%p, %#x, %p, %p, %s)\n",
1737         dst_buffer, file_format, src_surface, src_palette, wine_dbgstr_rect(src_rect));
1738
1739     if (!dst_buffer || !src_surface) return D3DERR_INVALIDCALL;
1740
1741     if (src_palette)
1742     {
1743         FIXME("Saving surfaces with palettized pixel formats not implemented yet\n");
1744         return D3DERR_INVALIDCALL;
1745     }
1746
1747     switch (file_format)
1748     {
1749         case D3DXIFF_BMP:
1750             encoder_clsid = &CLSID_WICBmpEncoder;
1751             break;
1752         case D3DXIFF_PNG:
1753             encoder_clsid = &CLSID_WICPngEncoder;
1754             break;
1755         case D3DXIFF_JPG:
1756             encoder_clsid = &CLSID_WICJpegEncoder;
1757             break;
1758         case D3DXIFF_DDS:
1759         case D3DXIFF_DIB:
1760         case D3DXIFF_HDR:
1761         case D3DXIFF_PFM:
1762         case D3DXIFF_TGA:
1763         case D3DXIFF_PPM:
1764             FIXME("File format %#x is not supported yet\n", file_format);
1765             return E_NOTIMPL;
1766         default:
1767             return D3DERR_INVALIDCALL;
1768     }
1769
1770     IDirect3DSurface9_GetDesc(src_surface, &src_surface_desc);
1771     if (src_rect)
1772     {
1773         if (src_rect->left == src_rect->right || src_rect->top == src_rect->bottom)
1774         {
1775             WARN("Invalid rectangle with 0 area\n");
1776             return D3DXCreateBuffer(64, dst_buffer);
1777         }
1778         if (src_rect->left < 0 || src_rect->top < 0)
1779             return D3DERR_INVALIDCALL;
1780         if (src_rect->left > src_rect->right || src_rect->top > src_rect->bottom)
1781             return D3DERR_INVALIDCALL;
1782         if (src_rect->right > src_surface_desc.Width || src_rect->bottom > src_surface_desc.Height)
1783             return D3DERR_INVALIDCALL;
1784
1785         width = src_rect->right - src_rect->left;
1786         height = src_rect->bottom - src_rect->top;
1787     }
1788     else
1789     {
1790         width = src_surface_desc.Width;
1791         height = src_surface_desc.Height;
1792     }
1793
1794     initresult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1795
1796     hr = CoCreateInstance(encoder_clsid, NULL, CLSCTX_INPROC_SERVER,
1797         &IID_IWICBitmapEncoder, (void **)&encoder);
1798     if (FAILED(hr)) goto cleanup_err;
1799
1800     hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
1801     if (FAILED(hr)) goto cleanup_err;
1802
1803     hr = IWICBitmapEncoder_Initialize(encoder, stream, WICBitmapEncoderNoCache);
1804     if (FAILED(hr)) goto cleanup_err;
1805
1806     hr = IWICBitmapEncoder_CreateNewFrame(encoder, &frame, &encoder_options);
1807     if (FAILED(hr)) goto cleanup_err;
1808
1809     hr = IWICBitmapFrameEncode_Initialize(frame, encoder_options);
1810     if (FAILED(hr)) goto cleanup_err;
1811
1812     hr = IWICBitmapFrameEncode_SetSize(frame, width, height);
1813     if (FAILED(hr)) goto cleanup_err;
1814
1815     pixel_format_guid = d3dformat_to_wic_guid(src_surface_desc.Format);
1816     if (!pixel_format_guid)
1817     {
1818         FIXME("Pixel format %#x is not supported yet\n", src_surface_desc.Format);
1819         hr = E_NOTIMPL;
1820         goto cleanup;
1821     }
1822
1823     memcpy(&wic_pixel_format, pixel_format_guid, sizeof(GUID));
1824     hr = IWICBitmapFrameEncode_SetPixelFormat(frame, &wic_pixel_format);
1825     d3d_pixel_format = wic_guid_to_d3dformat(&wic_pixel_format);
1826     if (SUCCEEDED(hr) && d3d_pixel_format != D3DFMT_UNKNOWN)
1827     {
1828         TRACE("Using pixel format %s %#x\n", debugstr_guid(&wic_pixel_format), d3d_pixel_format);
1829
1830         if (src_surface_desc.Format == d3d_pixel_format) /* Simple copy */
1831         {
1832             hr = IDirect3DSurface9_LockRect(src_surface, &locked_rect, src_rect, D3DLOCK_READONLY);
1833             if (SUCCEEDED(hr))
1834             {
1835                 IWICBitmapFrameEncode_WritePixels(frame, height,
1836                     locked_rect.Pitch, height * locked_rect.Pitch, locked_rect.pBits);
1837                 IDirect3DSurface9_UnlockRect(src_surface);
1838             }
1839         }
1840         else /* Pixel format conversion */
1841         {
1842             const PixelFormatDesc *src_format_desc, *dst_format_desc;
1843             struct volume size;
1844             DWORD dst_pitch;
1845             void *dst_data;
1846
1847             src_format_desc = get_format_info(src_surface_desc.Format);
1848             dst_format_desc = get_format_info(d3d_pixel_format);
1849             if (src_format_desc->format == D3DFMT_UNKNOWN || dst_format_desc->format == D3DFMT_UNKNOWN)
1850             {
1851                 FIXME("Unsupported pixel format conversion %#x -> %#x\n",
1852                     src_surface_desc.Format, d3d_pixel_format);
1853                 hr = E_NOTIMPL;
1854                 goto cleanup;
1855             }
1856
1857             if (src_format_desc->bytes_per_pixel > 4
1858                 || dst_format_desc->bytes_per_pixel > 4
1859                 || src_format_desc->block_height != 1 || src_format_desc->block_width != 1
1860                 || dst_format_desc->block_height != 1 || dst_format_desc->block_width != 1)
1861             {
1862                 FIXME("Format conversion missing %#x -> %#x\n",
1863                         src_surface_desc.Format, d3d_pixel_format);
1864                 hr = E_NOTIMPL;
1865                 goto cleanup;
1866             }
1867
1868             size.width = width;
1869             size.height = height;
1870             size.depth = 1;
1871             dst_pitch = width * dst_format_desc->bytes_per_pixel;
1872             dst_data = HeapAlloc(GetProcessHeap(), 0, dst_pitch * height);
1873             if (!dst_data)
1874             {
1875                 hr = E_OUTOFMEMORY;
1876                 goto cleanup;
1877             }
1878
1879             hr = IDirect3DSurface9_LockRect(src_surface, &locked_rect, src_rect, D3DLOCK_READONLY);
1880             if (SUCCEEDED(hr))
1881             {
1882                 copy_simple_data(locked_rect.pBits, locked_rect.Pitch, 0, &size, src_format_desc,
1883                     dst_data, dst_pitch, 0, &size, dst_format_desc, 0);
1884                 IDirect3DSurface9_UnlockRect(src_surface);
1885             }
1886
1887             IWICBitmapFrameEncode_WritePixels(frame, height, dst_pitch, dst_pitch * height, dst_data);
1888             HeapFree(GetProcessHeap(), 0, dst_data);
1889         }
1890
1891         hr = IWICBitmapFrameEncode_Commit(frame);
1892         if (SUCCEEDED(hr)) hr = IWICBitmapEncoder_Commit(encoder);
1893     }
1894     else WARN("Unsupported pixel format %#x\n", src_surface_desc.Format);
1895
1896     /* copy data from stream to ID3DXBuffer */
1897     hr = IStream_Stat(stream, &stream_stats, STATFLAG_NONAME);
1898     if (FAILED(hr)) goto cleanup_err;
1899
1900     if (stream_stats.cbSize.u.HighPart != 0)
1901     {
1902         hr = D3DXERR_INVALIDDATA;
1903         goto cleanup;
1904     }
1905     size = stream_stats.cbSize.u.LowPart;
1906
1907     hr = D3DXCreateBuffer(size, &buffer);
1908     if (FAILED(hr)) goto cleanup;
1909
1910     hr = GetHGlobalFromStream(stream, &stream_hglobal);
1911     if (SUCCEEDED(hr))
1912     {
1913         void *buffer_pointer = ID3DXBuffer_GetBufferPointer(buffer);
1914         void *stream_data = GlobalLock(stream_hglobal);
1915         memcpy(buffer_pointer, stream_data, size);
1916         GlobalUnlock(stream_hglobal);
1917         *dst_buffer = buffer;
1918     }
1919     else ID3DXBuffer_Release(buffer);
1920
1921 cleanup_err:
1922     if (FAILED(hr) && hr != E_OUTOFMEMORY)
1923         hr = D3DERR_INVALIDCALL;
1924
1925 cleanup:
1926     if (stream) IStream_Release(stream);
1927
1928     if (frame) IWICBitmapFrameEncode_Release(frame);
1929     if (encoder_options) IPropertyBag2_Release(encoder_options);
1930
1931     if (encoder) IWICBitmapEncoder_Release(encoder);
1932
1933     if (SUCCEEDED(initresult)) CoUninitialize();
1934
1935     return hr;
1936 }