LCOV - code coverage report
Current view: top level - source/lib/tex - tex_dds.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 193 218 88.5 %
Date: 2026-12-03 01:19:39 Functions: 12 14 85.7 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  *
       3             :  * Permission is hereby granted, free of charge, to any person obtaining
       4             :  * a copy of this software and associated documentation files (the
       5             :  * "Software"), to deal in the Software without restriction, including
       6             :  * without limitation the rights to use, copy, modify, merge, publish,
       7             :  * distribute, sublicense, and/or sell copies of the Software, and to
       8             :  * permit persons to whom the Software is furnished to do so, subject to
       9             :  * the following conditions:
      10             :  *
      11             :  * The above copyright notice and this permission notice shall be included
      12             :  * in all copies or substantial portions of the Software.
      13             :  *
      14             :  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
      15             :  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
      16             :  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
      17             :  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
      18             :  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
      19             :  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
      20             :  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      21             :  */
      22             : 
      23             : /*
      24             :  * DDS (DirectDraw Surface) codec.
      25             :  */
      26             : 
      27             : #include "precompiled.h"
      28             : 
      29             : #include "tex_codec.h"
      30             : 
      31             : #include "lib/alignment.h"
      32             : #include "lib/allocators/shared_ptr.h"
      33             : #include "lib/bits.h"
      34             : #include "lib/byte_order.h"
      35             : #include "lib/code_annotation.h"
      36             : #include "lib/debug.h"
      37             : #include "lib/lib.h"
      38             : #include "lib/os_path.h"
      39             : #include "lib/posix/posix_types.h"
      40             : #include "lib/status.h"
      41             : #include "lib/tex/tex.h"
      42             : #include "lib/tex/tex_internal.h"
      43             : 
      44             : #include <algorithm>
      45             : #include <bit>
      46             : #include <cstdlib>
      47             : #include <memory>
      48             : 
      49             : // NOTE: the convention is bottom-up for DDS, but there's no way to tell.
      50             : 
      51             : 
      52             : //-----------------------------------------------------------------------------
      53             : // S3TC decompression
      54             : //-----------------------------------------------------------------------------
      55             : 
      56             : // note: this code may not be terribly efficient. it's only used to
      57             : // emulate hardware S3TC support - if that isn't available, performance
      58             : // will suffer anyway due to increased video memory usage.
      59             : 
      60             : 
      61             : // for efficiency, we precalculate as much as possible about a block
      62             : // and store it here.
      63             : class S3tcBlock
      64             : {
      65             : public:
      66         521 :     S3tcBlock(size_t dxt, const std::uint8_t* RESTRICT block)
      67         521 :         : m_Dxt(dxt)
      68             :     {
      69             :         // (careful, 'dxt != 1' doesn't work - there's also DXT1a)
      70         521 :         const std::uint8_t* a_block = block;
      71         521 :         const std::uint8_t* c_block = (dxt == 3 || dxt == 5)? block+8 : block;
      72             : 
      73         521 :         PrecalculateAlpha(dxt, a_block);
      74         521 :         PrecalculateColor(dxt, c_block);
      75         521 :     }
      76             : 
      77        8336 :     void WritePixel(size_t pixel_idx, std::uint8_t* RESTRICT out) const
      78             :     {
      79        8336 :         ENSURE(pixel_idx < 16);
      80             : 
      81             :         // pixel index -> color selector (2 bit) -> color
      82        8336 :         const size_t c_selector = access_bit_tbl(c_selectors, pixel_idx, 2);
      83       33344 :         for(int i = 0; i < 3; i++)
      84       25008 :             out[i] = static_cast<std::uint8_t>(c[c_selector][i]);
      85             : 
      86             :         // if no alpha, done
      87        8336 :         if(m_Dxt == 1)
      88             :             return;
      89             : 
      90        4096 :         size_t a;
      91        4096 :         if(m_Dxt == 3)
      92             :         {
      93             :             // table of 4-bit alpha entries
      94           0 :             a = access_bit_tbl(a_bits, pixel_idx, 4);
      95           0 :             a |= a << 4; // expand to 8 bits (replicate high into low!)
      96             :         }
      97        4096 :         else if(m_Dxt == 5)
      98             :         {
      99             :             // pixel index -> alpha selector (3 bit) -> alpha
     100        4096 :             const size_t a_selector = access_bit_tbl(a_bits, pixel_idx, 3);
     101        4096 :             a = dxt5_a_tbl[a_selector];
     102             :         }
     103             :         // (m_Dxt == DXT1A)
     104             :         else
     105           0 :             a = c[c_selector][A];
     106        4096 :         out[A] = static_cast<std::uint8_t>(a & 0xFF);
     107             :     }
     108             : 
     109             : private:
     110             :     // pixel colors are stored as size_t[4]. size_t rather than std::uint8_t
     111             :     // protects from overflow during calculations, and padding to an even
     112             :     // size is a bit more efficient (even though we don't need the alpha
     113             :     // component).
     114             :     enum RGBA { R, G, B, A };
     115             : 
     116         690 :     static inline void mix_2_3(size_t dst[4], size_t c0[4], size_t c1[4])
     117             :     {
     118        2760 :         for(int i = 0; i < 3; i++) dst[i] = (c0[i]*2 + c1[i] + 1)/3;
     119             :     }
     120             : 
     121         176 :     static inline void mix_avg(size_t dst[4], size_t c0[4], size_t c1[4])
     122             :     {
     123         704 :         for(int i = 0; i < 3; i++) dst[i] = (c0[i]+c1[i])/2;
     124             :     }
     125             : 
     126             :     template<typename T>
     127       12432 :     static inline size_t access_bit_tbl(T tbl, size_t idx, size_t bit_width)
     128             :     {
     129       12432 :         size_t val = (tbl >> (idx*bit_width)) & bit_mask<T>(bit_width);
     130             :         return val;
     131             :     }
     132             : 
     133             :     // extract a range of bits and expand to 8 bits (by replicating
     134             :     // MS bits - see http://www.mindcontrol.org/~hplus/graphics/expand-bits.html ;
     135             :     // this is also the algorithm used by graphics cards when decompressing S3TC).
     136             :     // used to convert 565 to 32bpp RGB.
     137        1042 :     static inline size_t unpack_to_8(std::uint16_t c, size_t bits_below, size_t num_bits)
     138             :     {
     139        1042 :         const size_t num_filler_bits = 8-num_bits;
     140        1042 :         const size_t field = (size_t)bits(c, bits_below, bits_below+num_bits-1);
     141        1042 :         const size_t filler = field >> (num_bits-num_filler_bits);
     142        1042 :         return (field << num_filler_bits) | filler;
     143             :     }
     144             : 
     145         521 :     void PrecalculateAlpha(size_t dxt, const std::uint8_t* RESTRICT a_block)
     146             :     {
     147             :         // read block contents
     148         521 :         const std::uint8_t a0 = a_block[0], a1 = a_block[1];
     149         521 :         a_bits = read_le64(a_block);    // see below
     150             : 
     151         521 :         if(dxt == 5)
     152             :         {
     153             :             // skip a0,a1 bytes (data is little endian)
     154         256 :             a_bits >>= 16;
     155             : 
     156         256 :             const bool is_dxt5_special_combination = (a0 <= a1);
     157         256 :             std::uint8_t* a = dxt5_a_tbl;   // shorthand
     158         256 :             if(is_dxt5_special_combination)
     159             :             {
     160         182 :                 a[0] = a0;
     161         182 :                 a[1] = a1;
     162         182 :                 a[2] = (4*a0 + 1*a1 + 2)/5;
     163         182 :                 a[3] = (3*a0 + 2*a1 + 2)/5;
     164         182 :                 a[4] = (2*a0 + 3*a1 + 2)/5;
     165         182 :                 a[5] = (1*a0 + 4*a1 + 2)/5;
     166         182 :                 a[6] = 0;
     167         182 :                 a[7] = 255;
     168             :             }
     169             :             else
     170             :             {
     171          74 :                 a[0] = a0;
     172          74 :                 a[1] = a1;
     173          74 :                 a[2] = (6*a0 + 1*a1 + 3)/7;
     174          74 :                 a[3] = (5*a0 + 2*a1 + 3)/7;
     175          74 :                 a[4] = (4*a0 + 3*a1 + 3)/7;
     176          74 :                 a[5] = (3*a0 + 4*a1 + 3)/7;
     177          74 :                 a[6] = (2*a0 + 5*a1 + 3)/7;
     178          74 :                 a[7] = (1*a0 + 6*a1 + 3)/7;
     179             :             }
     180             :         }
     181         521 :     }
     182             : 
     183             : 
     184         521 :     void PrecalculateColor(size_t dxt, const std::uint8_t* RESTRICT c_block)
     185             :     {
     186             :         // read block contents
     187             :         // .. S3TC reference colors (565 format). the color table is generated
     188             :         //    from some combination of these, depending on their ordering.
     189         521 :         std::uint16_t rc[2];
     190        1563 :         for(int i = 0; i < 2; i++)
     191        1042 :             rc[i] = read_le16(c_block + 2*i);
     192             :         // .. table of 2-bit color selectors
     193         521 :         c_selectors = read_le32(c_block+4);
     194             : 
     195         521 :         const bool is_dxt1_special_combination = (dxt == 1 || dxt == DXT1A) && rc[0] <= rc[1];
     196             : 
     197             :         // c0 and c1 are the values of rc[], converted to 32bpp
     198        1563 :         for(int i = 0; i < 2; i++)
     199             :         {
     200        1042 :             c[i][R] = unpack_to_8(rc[i], 11, 5);
     201        1042 :             c[i][G] = unpack_to_8(rc[i],  5, 6);
     202        1042 :             c[i][B] = unpack_to_8(rc[i],  0, 5);
     203             :         }
     204             : 
     205             :         // c2 and c3 are combinations of c0 and c1:
     206         521 :         if(is_dxt1_special_combination)
     207             :         {
     208         176 :             mix_avg(c[2], c[0], c[1]);          // c2 = (c0+c1)/2
     209         704 :             for(int i = 0; i < 3; i++) c[3][i] = 0;  // c3 = black
     210         352 :             c[3][A] = (dxt == DXT1A)? 0 : 255;      // (transparent iff DXT1a)
     211             :         }
     212             :         else
     213             :         {
     214         345 :             mix_2_3(c[2], c[0], c[1]);          // c2 = 2/3*c0 + 1/3*c1
     215         345 :             mix_2_3(c[3], c[1], c[0]);          // c3 = 1/3*c0 + 2/3*c1
     216             :         }
     217         521 :     }
     218             : 
     219             :     // the 4 color choices for each pixel (RGBA)
     220             :     size_t c[4][4]; // c[i][RGBA_component]
     221             : 
     222             :     // (DXT5 only) the 8 alpha choices
     223             :     std::uint8_t dxt5_a_tbl[8];
     224             : 
     225             :     // alpha block; interpretation depends on dxt.
     226             :     std::uint64_t a_bits;
     227             : 
     228             :     // table of 2-bit color selectors
     229             :     std::uint32_t c_selectors;
     230             : 
     231             :     size_t m_Dxt;
     232             : };
     233             : 
     234             : 
     235             : struct S3tcDecompressInfo
     236             : {
     237             :     size_t dxt;
     238             :     size_t s3tc_block_size;
     239             :     size_t out_Bpp;
     240             :     std::uint8_t* out;
     241             : };
     242             : 
     243          10 : static void s3tc_decompress_level(size_t /*level*/, size_t level_w, size_t level_h,
     244             :     const std::uint8_t* RESTRICT level_data, size_t level_data_size, void* RESTRICT cbData)
     245             : {
     246          10 :     S3tcDecompressInfo* di = (S3tcDecompressInfo*)cbData;
     247          10 :     const size_t dxt             = di->dxt;
     248          10 :     const size_t s3tc_block_size = di->s3tc_block_size;
     249             : 
     250             :     // note: 1x1 images are legitimate (e.g. in mipmaps). they report their
     251             :     // width as such for glTexImage, but the S3TC data is padded to
     252             :     // 4x4 pixel block boundaries.
     253          10 :     const size_t blocks_w = DivideRoundUp(level_w, size_t(4));
     254          10 :     const size_t blocks_h = DivideRoundUp(level_h, size_t(4));
     255          10 :     const std::uint8_t* s3tc_data = level_data;
     256          10 :     ENSURE(level_data_size % s3tc_block_size == 0);
     257             : 
     258          50 :     for(size_t block_y = 0; block_y < blocks_h; block_y++)
     259             :     {
     260         561 :         for(size_t block_x = 0; block_x < blocks_w; block_x++)
     261             :         {
     262         521 :             S3tcBlock block(dxt, s3tc_data);
     263         521 :             s3tc_data += s3tc_block_size;
     264             : 
     265         521 :             size_t pixel_idx = 0;
     266        2605 :             for(int y = 0; y < 4; y++)
     267             :             {
     268             :                 // this is ugly, but advancing after x, y and block_y loops
     269             :                 // is no better.
     270        2084 :                 std::uint8_t* out = static_cast<std::uint8_t*>(di->out) + ((block_y*4+y)*blocks_w*4 + block_x*4) * di->out_Bpp;
     271       10420 :                 for(int x = 0; x < 4; x++)
     272             :                 {
     273        8336 :                     block.WritePixel(pixel_idx, out);
     274        8336 :                     out += di->out_Bpp;
     275        8336 :                     pixel_idx++;
     276             :                 }
     277             :             }
     278             :         }
     279             :     }
     280             : 
     281          10 :     ENSURE(s3tc_data == level_data + level_data_size);
     282          10 :     di->out += blocks_w*blocks_h * 16 * di->out_Bpp;
     283          10 : }
     284             : 
     285             : 
     286             : // decompress the given image (which is known to be stored as DXTn)
     287             : // effectively in-place. updates Tex fields.
     288          10 : static Status s3tc_decompress(Tex* t)
     289             : {
     290             :     // alloc new image memory
     291             :     // notes:
     292             :     // - dxt == 1 is the only non-alpha case.
     293             :     // - adding or stripping alpha channels during transform is not
     294             :     //   our job; we merely output the same pixel format as given
     295             :     //   (tex.cpp's plain transform could cover it, if ever needed).
     296          10 :     const size_t dxt = t->m_Flags & TEX_DXT;
     297          10 :     const size_t out_bpp = (dxt != 1)? 32 : 24;
     298          10 :     const size_t out_size = t->img_size() * out_bpp / t->m_Bpp;
     299          10 :     std::shared_ptr<std::uint8_t> decompressedData;
     300          10 :     AllocateAligned(decompressedData, out_size, g_PageSize);
     301             : 
     302          10 :     const size_t s3tc_block_size = (dxt == 3 || dxt == 5)? 16 : 8;
     303          10 :     S3tcDecompressInfo di = { dxt, s3tc_block_size, out_bpp/8, decompressedData.get() };
     304          10 :     const std::uint8_t* s3tc_data = t->get_data();
     305          10 :     const int levels_to_skip = (t->m_Flags & TEX_MIPMAPS)? 0 : TEX_BASE_LEVEL_ONLY;
     306          10 :     tex_util_foreach_mipmap(t->m_Width, t->m_Height, t->m_Bpp, s3tc_data, levels_to_skip, 4, s3tc_decompress_level, &di);
     307          10 :     t->m_Data = decompressedData;
     308          10 :     t->m_DataSize = out_size;
     309          10 :     t->m_Ofs = 0;
     310          10 :     t->m_Bpp = out_bpp;
     311          10 :     t->m_Flags &= ~TEX_DXT;
     312          10 :     return INFO::OK;
     313          10 : }
     314             : 
     315             : 
     316             : //-----------------------------------------------------------------------------
     317             : // DDS file format
     318             : //-----------------------------------------------------------------------------
     319             : 
     320             : // bit values and structure definitions taken from
     321             : // https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-reference
     322             : 
     323             : #pragma pack(push, 1)
     324             : 
     325             : // DDS_PIXELFORMAT.dwFlags
     326             : 
     327             : // This is used to distinguish RGBA from RGB and DXT1a from DXT1.
     328             : // we've seen some DXT3 files that don't have this set (which is nonsense;
     329             : // any image lacking alpha should be stored as DXT1).
     330             : #define DDPF_ALPHAPIXELS 0x00000001
     331             : // DDPF_ALPHA is used for uncompressed 8bpp greyscale, in which the data
     332             : // is stored in the alpha mask.
     333             : #define DDPF_ALPHA       0x00000002
     334             : #define DDPF_FOURCC      0x00000004
     335             : #define DDPF_RGB         0x00000040
     336             : 
     337             : struct DDS_PIXELFORMAT
     338             : {
     339             :     std::uint32_t dwSize;                       // size of structure (32)
     340             :     std::uint32_t dwFlags;                      // indicates which fields are valid
     341             :     std::uint32_t dwFourCC;                     // (DDPF_FOURCC) FOURCC code, "DXTn"
     342             :     std::uint32_t dwRGBBitCount;                // (DDPF_RGB) bits per pixel
     343             :     std::uint32_t dwRBitMask;
     344             :     std::uint32_t dwGBitMask;
     345             :     std::uint32_t dwBBitMask;
     346             :     std::uint32_t dwABitMask;                   // (DDPF_ALPHA or DDPF_ALPHAPIXELS)
     347             : };
     348             : 
     349             : 
     350             : // DDS_HEADER.dwFlags (none are optional)
     351             : #define DDSD_CAPS        0x00000001
     352             : #define DDSD_HEIGHT      0x00000002
     353             : #define DDSD_WIDTH       0x00000004
     354             : #define DDSD_PITCH       0x00000008 // used when texture is uncompressed
     355             : #define DDSD_PIXELFORMAT 0x00001000
     356             : #define DDSD_MIPMAPCOUNT 0x00020000
     357             : #define DDSD_LINEARSIZE  0x00080000 // used when texture is compressed
     358             : #define DDSD_DEPTH       0x00800000
     359             : 
     360             : // DDS_HEADER.dwCaps
     361             : #define DDSCAPS_MIPMAP   0x00400000 // optional
     362             : #define DDSCAPS_TEXTURE  0x00001000 // required
     363             : 
     364             : struct DDS_HEADER
     365             : {
     366             :     // (preceded by the FOURCC "DDS ")
     367             :     std::uint32_t dwSize;                    // size of structure (124)
     368             :     std::uint32_t dwFlags;                   // indicates which fields are valid
     369             :     std::uint32_t dwHeight;                  // (DDSD_HEIGHT) height of main image (pixels)
     370             :     std::uint32_t dwWidth;                   // (DDSD_WIDTH ) width  of main image (pixels)
     371             :     std::uint32_t dwPitchOrLinearSize;       // (DDSD_LINEARSIZE) size [bytes] of top level
     372             :                                    // (DDSD_PITCH) bytes per row (%4 = 0)
     373             :     std::uint32_t dwDepth;                   // (DDSD_DEPTH) vol. textures: vol. depth
     374             :     std::uint32_t dwMipMapCount;             // (DDSD_MIPMAPCOUNT) total # levels
     375             :     std::uint32_t dwReserved1[11];           // reserved
     376             :     DDS_PIXELFORMAT ddpf;          // (DDSD_PIXELFORMAT) surface description
     377             :     std::uint32_t dwCaps;                    // (DDSD_CAPS) misc. surface flags
     378             :     std::uint32_t dwCaps2;
     379             :     std::uint32_t dwCaps3;
     380             :     std::uint32_t dwCaps4;
     381             :     std::uint32_t dwReserved2;               // reserved
     382             : };
     383             : 
     384             : #pragma pack(pop)
     385             : 
     386             : 
     387          30 : static bool is_valid_dxt(size_t dxt)
     388             : {
     389          30 :     switch(dxt)
     390             :     {
     391             :     case 0:
     392             :     case 1:
     393             :     case DXT1A:
     394             :     case 3:
     395             :     case 5:
     396             :         return true;
     397           0 :     default:
     398           0 :         return false;
     399             :     }
     400             : }
     401             : 
     402             : 
     403             : // extract all information from DDS pixel format and store in bpp, flags.
     404             : // pf points to the DDS file's header; all fields must be endian-converted
     405             : // before use.
     406             : // output parameters invalid on failure.
     407          10 : static Status decode_pf(const DDS_PIXELFORMAT* pf, size_t& bpp, size_t& flags)
     408             : {
     409          10 :     bpp = 0;
     410          10 :     flags = 0;
     411             : 
     412             :     // check struct size
     413          10 :     if(read_le32(&pf->dwSize) != sizeof(DDS_PIXELFORMAT))
     414             :         return ERR::TEX_INVALID_SIZE;
     415             : 
     416             :     // determine type
     417          10 :     const size_t pf_flags = (size_t)read_le32(&pf->dwFlags);
     418             :     // .. uncompressed RGB/RGBA
     419          10 :     if(pf_flags & DDPF_RGB)
     420             :     {
     421           1 :         const size_t pf_bpp    = (size_t)read_le32(&pf->dwRGBBitCount);
     422           1 :         const size_t pf_r_mask = (size_t)read_le32(&pf->dwRBitMask);
     423           1 :         const size_t pf_g_mask = (size_t)read_le32(&pf->dwGBitMask);
     424           1 :         const size_t pf_b_mask = (size_t)read_le32(&pf->dwBBitMask);
     425           1 :         const size_t pf_a_mask = (size_t)read_le32(&pf->dwABitMask);
     426             : 
     427             :         // (checked below; must be set in case below warning is to be
     428             :         // skipped)
     429           1 :         bpp = pf_bpp;
     430             : 
     431           1 :         if(pf_flags & DDPF_ALPHAPIXELS)
     432             :         {
     433             :             // something weird other than RGBA or BGRA
     434           1 :             if(pf_a_mask != 0xFF000000)
     435           0 :                 WARN_RETURN(ERR::TEX_FMT_INVALID);
     436           1 :             flags |= TEX_ALPHA;
     437             :         }
     438             : 
     439             :         // make sure component ordering is 0xBBGGRR = RGB (see below)
     440           1 :         if(pf_r_mask != 0xFF || pf_g_mask != 0xFF00 || pf_b_mask != 0xFF0000)
     441             :         {
     442             :             // DDS_PIXELFORMAT in theory supports any ordering of R,G,B,A.
     443             :             // we need to upload to OpenGL, which can only receive BGR(A) or
     444             :             // RGB(A). the former still requires conversion (done by driver),
     445             :             // so it's slower. since the very purpose of supporting uncompressed
     446             :             // DDS is storing images in a format that requires no processing,
     447             :             // we do not allow any weird orderings that require runtime work.
     448             :             // instead, the artists must export with the correct settings.
     449             :             return ERR::TEX_FMT_INVALID;
     450             :         }
     451             : 
     452           1 :         RETURN_STATUS_IF_ERR(tex_validate_plain_format(bpp, (int)flags));
     453             :     }
     454             :     // .. uncompressed 8bpp greyscale
     455           9 :     else if(pf_flags & DDPF_ALPHA)
     456             :     {
     457           0 :         const size_t pf_bpp    = (size_t)read_le32(&pf->dwRGBBitCount);
     458           0 :         const size_t pf_a_mask = (size_t)read_le32(&pf->dwABitMask);
     459             : 
     460           0 :         bpp = pf_bpp;
     461             : 
     462           0 :         if(pf_bpp != 8)
     463             :             return ERR::TEX_FMT_INVALID;
     464             : 
     465           0 :         if(pf_a_mask != 0xFF)
     466             :             return ERR::TEX_FMT_INVALID;
     467           0 :         flags |= TEX_GREY;
     468             : 
     469           0 :         RETURN_STATUS_IF_ERR(tex_validate_plain_format(bpp, (int)flags));
     470             :     }
     471             :     // .. compressed
     472           9 :     else if(pf_flags & DDPF_FOURCC)
     473             :     {
     474             :         // set effective bpp and store DXT format in flags & TEX_DXT.
     475             :         // no endian conversion necessary - FOURCC() takes care of that.
     476           9 :         switch(pf->dwFourCC)
     477             :         {
     478           8 :         case FOURCC('D','X','T','1'):
     479           8 :             bpp = 4;
     480           8 :             if(pf_flags & DDPF_ALPHAPIXELS)
     481           0 :                 flags |= DXT1A | TEX_ALPHA;
     482             :             else
     483           8 :                 flags |= 1;
     484             :             break;
     485           0 :         case FOURCC('D','X','T','3'):
     486           0 :             bpp = 8;
     487           0 :             flags |= 3;
     488           0 :             flags |= TEX_ALPHA; // see DDPF_ALPHAPIXELS decl
     489           0 :             break;
     490           1 :         case FOURCC('D','X','T','5'):
     491           1 :             bpp = 8;
     492           1 :             flags |= 5;
     493           1 :             flags |= TEX_ALPHA; // see DDPF_ALPHAPIXELS decl
     494           1 :             break;
     495             : 
     496             :         default:
     497             :             return ERR::TEX_FMT_INVALID;
     498             :         }
     499             :     }
     500             :     // .. neither uncompressed nor compressed - invalid
     501             :     else
     502             :         return ERR::TEX_FMT_INVALID;
     503             : 
     504             :     return INFO::OK;
     505             : }
     506             : 
     507             : 
     508             : // extract all information from DDS header and store in w, h, bpp, flags.
     509             : // sd points to the DDS file's header; all fields must be endian-converted
     510             : // before use.
     511             : // output parameters invalid on failure.
     512          10 : static Status decode_sd(const DDS_HEADER* sd, size_t& w, size_t& h, size_t& bpp, size_t& flags)
     513             : {
     514             :     // check header size
     515          10 :     if(read_le32(&sd->dwSize) != sizeof(*sd))
     516             :         return ERR::CORRUPTED;
     517             : 
     518             :     // flags (indicate which fields are valid)
     519          10 :     const size_t sd_flags = (size_t)read_le32(&sd->dwFlags);
     520             :     // .. not all required fields are present
     521             :     // note: we can't guess dimensions - the image may not be square.
     522          10 :     const size_t sd_req_flags = DDSD_CAPS|DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT;
     523          10 :     if((sd_flags & sd_req_flags) != sd_req_flags)
     524             :         return ERR::TEX_INCOMPLETE_HEADER;
     525             : 
     526             :     // image dimensions
     527          10 :     h = (size_t)read_le32(&sd->dwHeight);
     528          10 :     w = (size_t)read_le32(&sd->dwWidth);
     529             : 
     530             :     // pixel format
     531          10 :     RETURN_STATUS_IF_ERR(decode_pf(&sd->ddpf, bpp, flags));
     532             : 
     533             :     // if the image is not aligned with the S3TC block size, it is stored
     534             :     // with extra pixels on the bottom left to fill up the space, so we need
     535             :     // to account for those when calculating how big it should be
     536          10 :     size_t stored_h, stored_w;
     537          10 :     if(flags & TEX_DXT)
     538             :     {
     539           9 :         stored_h = Align<4>(h);
     540           9 :         stored_w = Align<4>(w);
     541             :     }
     542             :     else
     543             :     {
     544           1 :         stored_h = h;
     545           1 :         stored_w = w;
     546             :     }
     547             : 
     548             :     // verify pitch or linear size, if given
     549          10 :     const size_t pitch = stored_w*bpp/8;
     550          10 :     const size_t sd_pitch_or_size = (size_t)read_le32(&sd->dwPitchOrLinearSize);
     551          10 :     if(sd_flags & DDSD_PITCH)
     552             :     {
     553           1 :         if(sd_pitch_or_size != Align<4>(pitch))
     554             :             return ERR::CORRUPTED;
     555             :     }
     556          10 :     if(sd_flags & DDSD_LINEARSIZE)
     557             :     {
     558             :         // some DDS tools mistakenly store the total size of all levels,
     559             :         // so allow values close to that as well
     560           9 :         const ssize_t totalSize = ssize_t(pitch*stored_h*1.333333f);
     561           9 :         if(sd_pitch_or_size != pitch*stored_h && std::abs(ssize_t(sd_pitch_or_size)-totalSize) > 64)
     562             :             return ERR::CORRUPTED;
     563             :     }
     564             :     // note: both flags set would be invalid; no need to check for that,
     565             :     // though, since one of the above tests would fail.
     566             : 
     567             :     // mipmaps
     568          10 :     if(sd_flags & DDSD_MIPMAPCOUNT)
     569             :     {
     570           7 :         const size_t mipmap_count = (size_t)read_le32(&sd->dwMipMapCount);
     571           7 :         if(mipmap_count)
     572             :         {
     573             :             // mipmap chain is incomplete
     574             :             // note: we need to account the DDS base level (1x1).
     575           7 :             const size_t maxSide{std::max(w, h)};
     576          14 :             if(mipmap_count != static_cast<size_t>(std::bit_width(maxSide) + !std::has_single_bit(maxSide)))
     577             :                 return ERR::TEX_FMT_INVALID;
     578           7 :             flags |= TEX_MIPMAPS;
     579             :         }
     580             :     }
     581             : 
     582             :     // check for volume textures
     583          10 :     if(sd_flags & DDSD_DEPTH)
     584             :     {
     585           0 :         const size_t depth = (size_t)read_le32(&sd->dwDepth);
     586           0 :         if(depth)
     587             :             return ERR::NOT_SUPPORTED;
     588             :     }
     589             : 
     590             :     // check caps
     591             :     // .. this is supposed to be set, but don't bail if not (pointless)
     592          10 :     if (!(sd->dwCaps & DDSCAPS_TEXTURE))
     593             :         return ERR::CORRUPTED;
     594             :     // .. sanity check: warn if mipmap flag not set (don't bail if not
     595             :     // because we've already made the decision).
     596          10 :     const bool mipmap_cap = (sd->dwCaps & DDSCAPS_MIPMAP) != 0;
     597          10 :     const bool mipmap_flag = (flags & TEX_MIPMAPS) != 0;
     598          10 :     if (mipmap_cap != mipmap_flag)
     599             :         return ERR::CORRUPTED;
     600             :     // note: we do not check for cubemaps and volume textures (not supported)
     601             :     // because the file may still have useful data we can read.
     602             : 
     603             :     return INFO::OK;
     604             : }
     605             : 
     606             : 
     607             : //-----------------------------------------------------------------------------
     608             : 
     609          14 : bool TexCodecDds::is_hdr(const std::uint8_t* file) const
     610             : {
     611          14 :     return *reinterpret_cast<const std::uint32_t*>(file) == FOURCC('D','D','S',' ');
     612             : }
     613             : 
     614             : 
     615           0 : bool TexCodecDds::is_ext(const OsPath& extension) const
     616             : {
     617           0 :     return extension == L".dds";
     618             : }
     619             : 
     620             : 
     621          20 : size_t TexCodecDds::hdr_size(const std::uint8_t* /*file*/) const
     622             : {
     623          20 :     return 4+sizeof(DDS_HEADER);
     624             : }
     625             : 
     626             : 
     627          10 : Status TexCodecDds::decode(std::uint8_t* RESTRICT data, size_t /*size*/, Tex* RESTRICT t) const
     628             : {
     629          10 :     const DDS_HEADER* sd = (const DDS_HEADER*)(data+4);
     630          10 :     RETURN_STATUS_IF_ERR(decode_sd(sd, t->m_Width, t->m_Height, t->m_Bpp, t->m_Flags));
     631             :     return INFO::OK;
     632             : }
     633             : 
     634             : 
     635           0 : Status TexCodecDds::encode(Tex* RESTRICT, DynArray* RESTRICT) const
     636             : {
     637             :     // note: do not return ERR::NOT_SUPPORTED et al. because that would
     638             :     // break tex_write (which assumes either this, 0 or errors are returned).
     639           0 :     return INFO::TEX_CODEC_CANNOT_HANDLE;
     640             : }
     641             : 
     642          30 : Status TexCodecDds::transform(Tex* t, size_t transforms) const
     643             : {
     644          30 :     size_t mipmaps = t->m_Flags & TEX_MIPMAPS;
     645          30 :     size_t dxt = t->m_Flags & TEX_DXT;
     646          30 :     ENSURE(is_valid_dxt(dxt));
     647             : 
     648          30 :     const size_t transform_mipmaps = transforms & TEX_MIPMAPS;
     649          30 :     const size_t transform_dxt = transforms & TEX_DXT;
     650             :     // requesting removal of mipmaps
     651          30 :     if(mipmaps && transform_mipmaps)
     652             :     {
     653             :         // we don't need to actually change anything except the flag - the
     654             :         // mipmap levels will just be treated as trailing junk
     655           7 :         t->m_Flags &= ~TEX_MIPMAPS;
     656           7 :         return INFO::OK;
     657             :     }
     658             :     // requesting decompression
     659          23 :     if(dxt && transform_dxt)
     660             :     {
     661          10 :         RETURN_STATUS_IF_ERR(s3tc_decompress(t));
     662             :         return INFO::OK;
     663             :     }
     664             :     // both are DXT (unsupported; there are no flags we can change while
     665             :     // compressed) or requesting compression (not implemented) or
     666             :     // both not DXT (nothing we can do) - bail.
     667             :     return INFO::TEX_CODEC_CANNOT_HANDLE;
     668             : }

Generated by: LCOV version 1.16