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