summaryrefslogtreecommitdiffstats
path: root/src/plugins/imageformats/tga/qtgafile.cpp
blob: d349a6188bb304578aa1fb20bf4c1f34a6b3c329 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the TGA plugin in the Qt ImageFormats module.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qtgafile.h"

#include <QtCore/QIODevice>
#include <QtCore/QDebug>
#include <QtCore/QDateTime>

struct TgaReader
{
    virtual ~TgaReader() {}
    virtual QRgb operator()(QIODevice *s) const = 0;
};

struct Tga16Reader : public TgaReader
{
    ~Tga16Reader() {}
    QRgb operator()(QIODevice *s) const
    {
        char ch1, ch2;
        if (s->getChar(&ch1) && s->getChar(&ch2)) {
            quint16 d = (int(ch1) & 0xFF) | ((int(ch2) & 0xFF) << 8);
            QRgb result = (d & 0x8000) ? 0xFF000000 : 0x00000000;
            result |= (d & 0x7C00 << 6) | (d & 0x03E0 << 3) | (d & 0x001F);
            return result;
        } else {
            return 0;
        }
    }
};

struct Tga24Reader : public TgaReader
{
    QRgb operator()(QIODevice *s) const
    {
        char r, g, b;
        if (s->getChar(&b) && s->getChar(&g) && s->getChar(&r))
            return qRgb(uchar(r), uchar(g), uchar(b));
        else
            return 0;
    }
};

struct Tga32Reader : public TgaReader
{
    QRgb operator()(QIODevice *s) const
    {
        char r, g, b, a;
        if (s->getChar(&b) && s->getChar(&g) && s->getChar(&r) && s->getChar(&a))
            return qRgba(uchar(r), uchar(g), uchar(b), uchar(a));
        else
            return 0;
    }
};

/*!
    \class QTgaFile
    \since 4.8
    \internal

    File data container for a TrueVision Graphics format file.

    Format is as described here:
    http://local.wasp.uwa.edu.au/~pbourke/dataformats/tga/
    http://netghost.narod.ru/gff2/graphics/summary/tga.htm

    Usage is:
    \code
    QTgaFile tga(myFile);
    QImage tgaImage;
    if (tga.isValid())
        tgaImage = tga.readImage();
    \endcode

    The class is designed to handle sequential and non-sequential
    sources, so during construction the mHeader is read.  Then during
    the readImage() call the rest of the data is read.

    After passing myFile to the constructor, if the QIODevice *myFile
    is read, or has seek() called, the results are undefined - so don't
    do that.
*/

/*!
    Construct a new QTgaFile object getting data from \a device.

    The object does not take ownership of the \a device, but until the
    object is destroyed do not do any non-const operations, eg seek or
    read on the device.
*/
QTgaFile::QTgaFile(QIODevice *device)
    : mDevice(device)
{
    ::memset(mHeader, 0, HeaderSize);
    if (!mDevice->isReadable())
    {
        mErrorMessage = tr("Could not read image data");
        return;
    }
    if (mDevice->isSequential())
    {
        mErrorMessage = tr("Sequential device (eg socket) for image read not supported");
        return;
    }
    if (!mDevice->seek(0))
    {
        mErrorMessage = tr("Seek file/device for image read failed");
        return;
    }
    int bytes = device->read((char*)mHeader, HeaderSize);
    if (bytes != HeaderSize)
    {
        mErrorMessage = tr("Image header read failed");
        return;
    }
    if (mHeader[ImageType] != 2)
    {
        // TODO: should support other image types
        mErrorMessage = tr("Image type not supported");
        return;
    }
    int bitsPerPixel = mHeader[PixelDepth];
    bool validDepth = (bitsPerPixel == 16 || bitsPerPixel == 24 || bitsPerPixel == 32);
    if (!validDepth)
    {
        mErrorMessage = tr("Image depth not valid");
    }
    int curPos = mDevice->pos();
    int fileBytes = mDevice->size();
    if (!mDevice->seek(fileBytes - FooterSize))
    {
        mErrorMessage = tr("Could not seek to image read footer");
        return;
    }
    char footer[FooterSize];
    bytes = mDevice->read((char*)footer, FooterSize);
    if (bytes != FooterSize)
    {
        mErrorMessage = tr("Could not read footer");
    }
    if (qstrncmp(&footer[SignatureOffset], "TRUEVISION-XFILE", 16) != 0)
    {
        mErrorMessage = tr("Image type (non-TrueVision 2.0) not supported");
    }
    if (!mDevice->seek(curPos))
    {
        mErrorMessage = tr("Could not reset to read data");
    }
}

/*!
    \internal
    Destroy the device, recovering any resources.
*/
QTgaFile::~QTgaFile()
{
}

/*!
    \internal
    Reads an image file from the QTgaFile's device, and returns it.

    This method seeks to the absolute position of the image data in the file,
    so no assumptions are made about where the devices read pointer is when this
    method is called.  For this reason only random access devices are supported.

    If the constructor completed successfully, such that isValid() returns true,
    then this method is likely to succeed, unless the file is somehow corrupted.

    In the case that the read fails, the QImage returned will be null, such that
    QImage::isNull() will be true.
*/
QImage QTgaFile::readImage()
{
    if (!isValid())
        return QImage();

    int offset = mHeader[IdLength];  // Mostly always zero

    // Even in TrueColor files a color pallette may be present
    if (mHeader[ColorMapType] == 1)
        offset += littleEndianInt(&mHeader[CMapLength]) * littleEndianInt(&mHeader[CMapDepth]);

    mDevice->seek(HeaderSize + offset);

    char dummy;
    for (int i = 0; i < offset; ++i)
        mDevice->getChar(&dummy);

    int bitsPerPixel = mHeader[PixelDepth];
    int imageWidth = width();
    int imageHeight = height();

    unsigned char desc = mHeader[ImageDescriptor];
    //unsigned char xCorner = desc & 0x10; // 0 = left, 1 = right
    unsigned char yCorner = desc & 0x20; // 0 = lower, 1 = upper

    QImage im(imageWidth, imageHeight, QImage::Format_ARGB32);
    TgaReader *reader = 0;
    if (bitsPerPixel == 16)
        reader = new Tga16Reader();
    else if (bitsPerPixel == 24)
        reader = new Tga24Reader();
    else if (bitsPerPixel == 32)
        reader = new Tga32Reader();
    TgaReader &read = *reader;

    // For now only deal with yCorner, since no one uses xCorner == 1
    // Also this is upside down, since Qt has the origin flipped
    if (yCorner)
    {
        for (int y = 0; y < imageHeight; ++y)
            for (int x = 0; x < imageWidth; ++x)
                im.setPixel(x, y, read(mDevice));
    }
    else
    {
        for (int y = imageHeight - 1; y >= 0; --y)
            for (int x = 0; x < imageWidth; ++x)
                im.setPixel(x, y, read(mDevice));
    }

    delete reader;

    // TODO: add processing of TGA extension information - ie TGA 2.0 files
    return im;
}