TextureDataLoadStore.cc 21.7 KB
Newer Older
1
2
3
4
5
/***********************************************************************
 * Copyright 2011-2012 Computer Graphics Group RWTH Aachen University. *
 * All rights reserved.                                                *
 * Distributed under the terms of the MIT License (see LICENSE.TXT).   *
 **********************************************************************/
6

Robert Menzel's avatar
Robert Menzel committed
7
#include <ACGL/OpenGL/Data/TextureDataLoadStore.hh>
8
#include <ACGL/OpenGL/Tools.hh>
9
#include <ACGL/Base/FileHelpers.hh>
Robert Menzel's avatar
Robert Menzel committed
10
#include <ACGL/Utils/Memory.hh>
11
12
13
14
15

// for the screenshot function:
#include <ACGL/OpenGL/Objects/FrameBufferObject.hh>
#include <cstdio>
#include <ctime>
16
17

#include <fstream>
Robert Menzel's avatar
Robert Menzel committed
18
#include "lodepng/lodepng.h"
19
#include "rgbe/rgbe.hh"
20

21
22
23
#ifdef ACGL_COMPILE_WITH_QT
#include <QImage>
#include <QGLWidget>
Robert Menzel's avatar
Robert Menzel committed
24
25
#include <QByteArray>
#include <QImageWriter>
26
27
#endif

28
29
30
31
32
33
34
35
36
//
// OpenEXR:
// Only compile with OpenEXR support if explicitly wanted so.
// Note that the application has to be linked to libIlmImf and libIex and the include path has to be set.
// (in your CMakeLists.txt add:
//   ADD_DEFINITIONS(-DACGL_BUILD_WITH_EXR)
//   ADD_DEFINITIONS(-I"/usr/include/OpenEXR/")
//   SET(LIBRARIES ${LIBRARIES} "-lIlmImf -lIex")
//
37
38
39
40
41
42
43
#ifdef ACGL_BUILD_WITH_EXR
//#include <ImfInputFile.h>
#include <ImfRgbaFile.h>
using namespace Imf;
using namespace Imath;
#endif

44
45
46
47
using namespace ACGL;
using namespace ACGL::OpenGL;
using namespace ACGL::Utils;

Robert Menzel's avatar
Robert Menzel committed
48
49
50
namespace ACGL{
namespace OpenGL{

51
52
53
///////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                               generic load/save
///////////////////////////////////////////////////////////////////////////////////////////////////
54

55
56
57
58
SharedTextureData loadTextureData(const std::string &_filename)
{
    // lower case file ending:
    std::string fileEnding = Base::FileHelpers::getFileEnding( _filename );
59

60
61
    if (fileEnding == "png") {
        return loadTextureDataFromLodepng( _filename );
62
63
    } else if (fileEnding == "hdr") {
        return loadTextureDataFromRGBE( _filename );
64
65
    } else if (fileEnding == "exr") {
        return loadTextureDataFromEXR( _filename );
66
67
    } else if (fileEnding == "ppm") {
        return loadTextureDataFromPNM( _filename );
68
69
70
71
72
73
74
75
76
77
    }
#ifdef ACGL_COMPILE_WITH_QT
    else if (   fileEnding == "bmp" || fileEnding == "jpg" || fileEnding == "jpeg"
             || fileEnding == "png" || fileEnding == "pbm" || fileEnding == "ppm"
             || fileEnding == "tif" || fileEnding == "tiff"|| fileEnding == "xbm"
             || fileEnding == "xpm" || fileEnding == "pgm") {
        return loadTextureDataFromQT( _filename );
    }
#endif
    else {
78
        error() << "texture file format of " << _filename << " not supported" << std::endl;
79
80
    }

81
82
    return SharedTextureData();
}
83

84
85
86
87
bool saveTextureData(const SharedTextureData &_textureData, const std::string &_filename)
{
    // lower case file ending:
    std::string fileEnding = Base::FileHelpers::getFileEnding( _filename );
88

89
90
    if (fileEnding == "png") {
        return saveTextureDataToLodepng( _textureData, _filename );
91
    }
92
93
94
95
96
97
98
99
100
101
102
#ifdef ACGL_COMPILE_WITH_QT
    else if (   fileEnding == "bmp" || fileEnding == "jpg" || fileEnding == "jpeg"
             || fileEnding == "png" || fileEnding == "ppm"
             || fileEnding == "tif" || fileEnding == "tiff"|| fileEnding == "xbm"
             || fileEnding == "xpm") {
        return saveTextureDataToQT( _textureData, _filename );
    }
#endif
    else if (fileEnding == "ppm") {
        return saveTextureDataToPPM( _textureData, _filename );
    } else {
103
        error() << "texture file format of " << _filename << " not supported" << std::endl;
104
105
    }

106
107
    return false;
}
108
109


110
111
112
113
bool saveScreenshot( const std::string &_prefix, const std::string _fileEnding )
{
    time_t rawtime;
    time( &rawtime );
114

115
116
117
    char timestring[30];
    strftime( timestring, 30, "_%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) );

Robert Menzel's avatar
Robert Menzel committed
118
119
120
121
122
123
124
125
126
    static int i = 0;
    i++;

    std::string filename = _prefix + timestring + "_" + ACGL::Base::StringOperations::toString(i) + "." + _fileEnding;

    ACGL::OpenGL::SharedTextureData screenShot = FrameBufferObject::getImageData();
    bool success = ACGL::OpenGL::saveTextureData( screenShot, filename );

    return success;
127
}
Robert Menzel's avatar
Robert Menzel committed
128

129
130
131
///////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                           library specific load
///////////////////////////////////////////////////////////////////////////////////////////////////
Robert Menzel's avatar
Robert Menzel committed
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

SharedTextureData loadTextureDataFromLodepng(const std::string &_filename)
{
    SharedTextureData data;

    unsigned int errorCode;
    unsigned int width, height;
    unsigned char* png;
    size_t pngsize;
    LodePNGState state;

    // Load the PNG file from disk

    lodepng_state_init(&state);

    errorCode = lodepng_load_file(&png, &pngsize, _filename.c_str());
    if(errorCode)
    {
        ACGL::Utils::error() << "LodePNG error while loading file " << _filename << " - " << errorCode << ": " << lodepng_error_text(errorCode) << std::endl;
        return data;
    }

    // Extract metadata (bit depth, color type)

    errorCode = lodepng_inspect(&width, &height, &state, png, pngsize);
    if(errorCode)
    {
        ACGL::Utils::error() << "LodePNG error " << errorCode << ": " << lodepng_error_text(errorCode) << std::endl;
        return data;
    }

    unsigned int bitdepth = state.info_png.color.bitdepth;
    LodePNGColorType colorType = state.info_png.color.colortype;

    unsigned int channels = 0;
    GLenum glFormat = 0;

    if(colorType == LCT_GREY)       { channels = 1; glFormat = GL_RED;  }
    if(colorType == LCT_GREY_ALPHA) { channels = 2; glFormat = GL_RG;   }
    if(colorType == LCT_RGB)        { channels = 3; glFormat = GL_RGB;  }
    if(colorType == LCT_RGBA)       { channels = 4; glFormat = GL_RGBA; }

    GLenum glType = 0;
    if(bitdepth ==  8) glType = GL_UNSIGNED_BYTE;
    if(bitdepth == 16) glType = GL_UNSIGNED_SHORT;
    if(bitdepth == 32) glType = GL_UNSIGNED_INT;

    if(channels == 0 || glFormat == 0 || glType == 0)
    {
        ACGL::Utils::error() << "Could not load " << _filename << ": " << "unsupported bit depth or format" << std::endl;
        return data;
    }

    // Decode the image

    unsigned char* image;
    errorCode = lodepng_decode_memory(&image, &width, &height, png, pngsize, colorType, bitdepth);
    if(errorCode)
    {
        ACGL::Utils::error() << "LodePNG error while loading file " << _filename << " - " << errorCode << ": " << lodepng_error_text(errorCode) << std::endl;
        return data;
    }

    free(png);

    // Wrap the data in a TextureData object

    data = SharedTextureData(new TextureData());
    data->setData((GLubyte*)image);
    data->setWidth(width);
    data->setHeight(height);
    data->setType(glType);
    data->setFormat(glFormat);

    return data;
}

209
210
211
212

#ifdef ACGL_COMPILE_WITH_QT
//! loads from the QT library
SharedTextureData loadTextureDataFromQT(const std::string &_filename)
Robert Menzel's avatar
Robert Menzel committed
213
{
Robert Menzel's avatar
Robert Menzel committed
214
    SharedTextureData data = SharedTextureData( new TextureData() );
Robert Menzel's avatar
Robert Menzel committed
215

216
    QImage image = QImage( QString(_filename.c_str()) );
Robert Menzel's avatar
Robert Menzel committed
217

218
219
220
221
222
    if (image.isNull())
    {
        ACGL::Utils::error() << "Loading image " << _filename << " has failed!" << std::endl;
        return data;
    }
Robert Menzel's avatar
Robert Menzel committed
223

224
225
226
227
228
229
    image = QGLWidget::convertToGLFormat(image);
    GLubyte *pImageData = new GLubyte[image.byteCount()];
    memcpy(pImageData, image.bits(), image.byteCount());
    data->setData(   pImageData     );
    data->setWidth(  image.width()  );
    data->setHeight( image.height() );
Robert Menzel's avatar
Robert Menzel committed
230

231
232
233
234
    return data;
}
#endif

235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
SharedTextureData loadTextureDataFromRGBE(const std::string &_filename)
{
    SharedTextureData data = SharedTextureData( new TextureData() );

    FILE* f = fopen(_filename.c_str(), "rb");

    int texWidth, texHeight;
    RGBE_ReadHeader(f, &texWidth, &texHeight, NULL);
    GLubyte* tempdata = new GLubyte[ sizeof(GL_FLOAT) * 3 * texWidth * texHeight];
    RGBE_ReadPixels_RLE(f, (float*)tempdata, texWidth, texHeight);
    fclose(f);

    data->setData(   tempdata  );
    data->setHeight( texHeight );
    data->setWidth(  texWidth  );
    data->setFormat( GL_RGB );
    data->setType(   GL_FLOAT  );

    return data;
}

256
257
258
SharedTextureData loadTextureDataFromEXR(const std::string &_filename)
{
#ifndef ACGL_BUILD_WITH_EXR
259
    error() << "can't load EXR file " << _filename << " ACGL was not build with EXR support" << std::endl;
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
    return SharedTextureData();
#else
    SharedTextureData data = SharedTextureData( new TextureData() );
    try {
        // see GPU gems 1:
        Imf::RgbaInputFile in( _filename.c_str() );

        Imath::Box2i window = in.dataWindow();

        Imath::V2i dimension( window.max.x - window.min.x +1,
                              window.max.y - window.min.y +1);

        unsigned char *buffer = (unsigned char *) new Imf::Rgba[ dimension.x*dimension.y ];

        int dx = window.min.x;
        int dy = window.min.y;

        in.setFrameBuffer( (Imf::Rgba*)buffer-dx-dy*dimension.x, 1, dimension.x );
        in.readPixels( window.min.y, window.max.y );

        data->setData(   buffer  );
        data->setHeight( dimension.y );
        data->setWidth(  dimension.x  );
        data->setFormat( GL_RGBA );
        data->setType(   GL_HALF_FLOAT  );
    } catch(Iex::BaseExc &e) {
        error() << "EXR loading failed: " << e.what() << std::endl;
        return SharedTextureData();
    }

    return data;
#endif
}

294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
enum loadTextureDataFromPNM_InputDataFormat
{
    PLAIN_TEXT_BITMAP,  // used by P1
    PLAIN_TEXT_DECIMAL, // used by P2 and P3
    BINARY_PACKED,      // used by P4
    BINARY_BYTES,       // used by P5 and P6
    BINARY_WORDS        // used by P5 and P6
};

void loadTextureDataFromPNM_skipWhitespace(std::istream& _in, uint_t _max = std::numeric_limits<std::streamsize>::max())
{
    uint_t skipped = 0;
    while(isspace(_in.peek()) && skipped < _max)
    {
        _in.ignore(1);
        skipped++;
    }
}

std::istream& loadTextureDataFromPNM_filterPNMComments(std::istream& _in)
{
    loadTextureDataFromPNM_skipWhitespace(_in);

    // When the stream starts with a #, throw away all following characters until the next newline
    // TODO: this does not entirely conform to the PNM specs, where # characters may appear anywhere, not just at the beginning of fields
    while(_in.peek() == '#')
    {
        _in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        loadTextureDataFromPNM_skipWhitespace(_in);
    }
    return _in;
}

SharedTextureData loadTextureDataFromPNM(const std::string &_filename)
{
    std::ifstream fileStream( _filename, std::ifstream::in );

    if (!fileStream.good()) {
        error() << "could not open file " << _filename << std::endl;
        return SharedTextureData();
    }

    SharedTextureData texture = SharedTextureData( new TextureData() );

    // Read the PNM header
    std::string header;
    loadTextureDataFromPNM_filterPNMComments(fileStream) >> header;

    // The header version determines the format of the data
    loadTextureDataFromPNM_InputDataFormat inputDataFormat = BINARY_BYTES; // set it to something to prevent 'may be uninitialized' warnings (which can't occur here)
    uint_t components;
    if     (header == "P1") { components = 1; inputDataFormat = PLAIN_TEXT_BITMAP; }
    else if(header == "P2") { components = 1; inputDataFormat = PLAIN_TEXT_DECIMAL; }
    else if(header == "P3") { components = 3; inputDataFormat = PLAIN_TEXT_DECIMAL; }
    else if(header == "P4") { components = 1; inputDataFormat = BINARY_PACKED; }
    else if(header == "P5") { components = 1; /* the data format will be determined later */ }
    else if(header == "P6") { components = 3; /* the data format will be determined later */ }
    else
    {
        error() << "could not load " << _filename << ": invalid header" << std::endl;
        fileStream.close();
        return SharedTextureData();
    }

    // Read the width and height of the image
    uint_t width, height;
    loadTextureDataFromPNM_filterPNMComments(fileStream) >> width;
    loadTextureDataFromPNM_filterPNMComments(fileStream) >> height;
    if(!fileStream.good() || width == 0 || height == 0)
    {
        error() << "could not load " << _filename << ": invalid image size" << std::endl;
        fileStream.close();
        return SharedTextureData();
    }

    // The max value is only present in the P2, P3, P5, P6 versions of the PNM format
    uint_t maxValue = 1;
    if(header == "P2" || header == "P3" || header == "P5" || header == "P6")
    {
        loadTextureDataFromPNM_filterPNMComments(fileStream) >> maxValue;

        if(!fileStream.good() || maxValue == 0)
        {
            error() << "could not load " << _filename << ": invalid value range" << std::endl;
            fileStream.close();
            return SharedTextureData();
        }
    }

    // The binary formats P5 and P6 use either bytes or words of data for each element, depending on the maxValue
    if(header == "P5" || header == "P6")
    {
        if     (maxValue <   256) { inputDataFormat = BINARY_BYTES; }
        else if(maxValue < 65536) { inputDataFormat = BINARY_WORDS; }
        else
        {
            error() << "could not load " << _filename << ": max value out of bounds" << std::endl;
            fileStream.close();
            return SharedTextureData();
        }
    }

    // If the image data has maxValue of 255 or 1, we return a GL_UNSIGNED_BYTE texture,
    // otherwise the values are normalized and returned as a GL_FLOAT texture
    GLenum outputDataType = GL_FLOAT;
    if(maxValue == 255 || maxValue == 1)
        outputDataType = GL_UNSIGNED_BYTE;

    // The data section is separated by a single whitespace
    loadTextureDataFromPNM_skipWhitespace(fileStream, 1);

    // Now, read in the data
    // No comments (#) are expected during this section
    unsigned char* data = new unsigned char[width * height * components * getGLTypeSize(outputDataType)];
    uint_t elementsRead = 0;
    while (fileStream.good() && elementsRead < (width * height * components))
    {
        // Read in one element
        // The exact procedure is based on the input data format

        uint_t elem;
        if(inputDataFormat == PLAIN_TEXT_DECIMAL)
        {
            fileStream >> elem;
        }
        else if(inputDataFormat == BINARY_BYTES)
        {
            uint8_t byte;
            fileStream.read((char*)&byte, 1);
            elem = byte;
        }
        else if(inputDataFormat == BINARY_WORDS)
        {
            uint8_t word;
            fileStream.read((char*)&word, 2);
            elem = word;
        }
        else if(inputDataFormat == PLAIN_TEXT_BITMAP)
        {
            loadTextureDataFromPNM_skipWhitespace(fileStream);
            char c;
            fileStream.read(&c, 1);
            if     (c == '0') elem = 0;
            else if(c == '1') elem = 1;
            else              break;
        }
        else if(inputDataFormat == BINARY_PACKED)
        {
            uint_t offset = elementsRead % 8;
            uint8_t byte = fileStream.peek();

            if(byte & 1<<(7-offset)) elem = 1;
            else                     elem = 0;

            if(offset == 7)
                fileStream.ignore(1);
        }

        if(!fileStream.good()) break;

        // Store the element in the data array
        if(outputDataType == GL_UNSIGNED_BYTE)
        {
            if(maxValue == 1) elem *= 255; // Bitmap values are normalized to 0..255
            data[elementsRead * getGLTypeSize(outputDataType)] = (GLubyte)elem;
        }
        else if(outputDataType == GL_FLOAT)
        {
            // Float values are normalized to 0..1
            GLfloat normalized = (GLfloat)elem / (GLfloat)maxValue;
            GLfloat* position = (GLfloat*)&data[elementsRead * getGLTypeSize(outputDataType)];
            *position = normalized;
        }

        elementsRead++;
    }
    fileStream.close();

    if(elementsRead != width * height * components)
    {
        error() << "could not load " << _filename << ": unexpected EOF" << std::endl;
        return SharedTextureData();
    }

    texture->setData(data); // data will get deleted by the TextureData destructor!
    texture->setDepth(1);   // 2D so, depth is 1
    texture->setHeight(height);
    texture->setWidth(width);
#ifdef ACGL_OPENGL_ES
    texture->setFormat(GL_RGB);
#else
    texture->setFormat(components == 3 ? GL_RGB : GL_RED);
#endif
    texture->setType(outputDataType);

    return texture;
}

492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
///////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                           library specific save
///////////////////////////////////////////////////////////////////////////////////////////////////

bool saveTextureDataToPPM(const SharedTextureData& _textureData, const std::string &_filename)
{
    std::ofstream outFileStream(_filename.c_str(), std::ios_base::out | std::ios_base::binary);

    if(!outFileStream.good())
    {
        error() << "saveTextureDataToPPM: Could not open file " << _filename << std::endl;
        return false;
    }

    // Use the binary-encoded RGB texture format
    outFileStream << "P6" << std::endl;

    // Width and height
    outFileStream << _textureData->getWidth() << " " << _textureData->getHeight() << std::endl;

    // Maximum value
    uint_t maxValue;
    if(_textureData->getType() == GL_UNSIGNED_BYTE)
    {
        maxValue = 255;
    }
    else
    {
        error() << "saveTextureDataToPPM: Unsupported texture type, must be GL_UNSIGNED_BYTE" << std::endl;
        return false;
    }
    outFileStream << maxValue;

    // Single whitespace as a delimiter
    outFileStream << "\n";

Robert Menzel's avatar
Robert Menzel committed
528
529
    GLsizei channelCount = _textureData->getNumberOfChannels();

530
531
532
533
534
    // Now, write the image data in binary format
    for(GLsizei y = 0; y < _textureData->getHeight(); ++y)
    {
        for(GLsizei x = 0; x < _textureData->getWidth(); ++x)
        {
Robert Menzel's avatar
Robert Menzel committed
535
536
            GLsizei row = _textureData->getHeight() - y - 1; // from bottom to the top to mirror the image
            GLsizei i = channelCount * (row * _textureData->getWidth() + x) + (row * _textureData->getPadding());
537

Robert Menzel's avatar
Robert Menzel committed
538
539
540
541
542
543
544
545
            unsigned char r =                     _textureData->getData()[(i + 0)];
            unsigned char g = (channelCount > 1)? _textureData->getData()[(i + 1)] : 0;
            unsigned char b = (channelCount > 2)? _textureData->getData()[(i + 2)] : 0;

            outFileStream.put( r );
            outFileStream.put( g );
            outFileStream.put( b );
            // ignore alpha if there is an alpha
546
        }
Robert Menzel's avatar
Robert Menzel committed
547
548
    }

549
550
    outFileStream.close();
    return true;
Robert Menzel's avatar
Robert Menzel committed
551
552
}

553
bool saveTextureDataToLodepng( const SharedTextureData &_data, const std::string &_filename )
Robert Menzel's avatar
Robert Menzel committed
554
{
Robert Menzel's avatar
Robert Menzel committed
555
556
557
558
    if (_data->getPadding() != 0) {
        error() << "png saving via lodepng does not support padding per row" << std::endl;
        return false;
    }
Robert Menzel's avatar
Robert Menzel committed
559
    GLenum channelDataType    = _data->getType();
Robert Menzel's avatar
Robert Menzel committed
560
    unsigned int channelCount = _data->getNumberOfChannels();
Robert Menzel's avatar
Robert Menzel committed
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613

    int channelBitCount = 0;
    if (channelDataType == GL_BYTE  || channelDataType == GL_UNSIGNED_BYTE)  channelBitCount = 8;
    if (channelDataType == GL_SHORT || channelDataType == GL_UNSIGNED_SHORT) channelBitCount = 16;
    if (channelDataType == GL_INT   || channelDataType == GL_UNSIGNED_INT)   channelBitCount = 32;

    unsigned char *processedData;
    if ( channelBitCount == 8 ) {
       processedData = preProcess<unsigned char>( _data );
    } else if ( channelBitCount == 16 ) {
        processedData = preProcess<unsigned short>( _data );
    } else if ( channelBitCount == 32 ) {
        processedData = preProcess<unsigned int>( _data );

        // no 32 bit save support -> reduce to 16 bit
        uint32_t *original = (uint32_t*) processedData;
        uint16_t *processedData16 = new uint16_t[ channelCount*_data->getWidth() * _data->getHeight() ];

        for (unsigned int i = 0; i < channelCount*_data->getWidth() * _data->getHeight(); ++i) {
            processedData16[i] = (uint16_t) original[i];
        }
        channelBitCount = 16;
        processedData = (unsigned char*) processedData16;

        delete[] original;

    } else {
        error() << "savePNG does not support this data type (yet), could not write " << _filename << std::endl;
        return false;
    }


    LodePNGColorType colorType;
    if (channelCount == 1) colorType = LCT_GREY;
    if (channelCount == 2) colorType = LCT_GREY_ALPHA;
    if (channelCount == 3) colorType = LCT_RGB;
    if (channelCount == 4) colorType = LCT_RGBA;

    unsigned int errorCode = lodepng_encode_file(_filename.c_str(),
                                    processedData, _data->getWidth(), _data->getHeight(),
                                    colorType, channelBitCount );

    delete[] processedData;

    //if there's an error, display it
    if (errorCode) {
        error() << "encoder error " << errorCode << ": "<< lodepng_error_text(errorCode) << std::endl;
        return false;
    }

    return true;
}

614
615
616
#ifdef ACGL_COMPILE_WITH_QT
bool saveTextureDataToQT( const SharedTextureData &_data, const std::string &_filename )
{
Robert Menzel's avatar
Robert Menzel committed
617
618
619
620
621
622
623
624
625
626
627
628
629
630
    QImage::Format format = QImage::Format_ARGB32;

    if ( pointerAlignment( (void*)_data->getData() ) < 4 ) {
        error() << "image data is not 32bit aligned, QT will not be able to handle that" << std::endl;
        return false;
    }

    GLenum glFormat = _data->getFormat();
    if (glFormat == GL_RGB) {
        format = QImage::Format_RGB888;
        if (_data->getPackAlignment() < 4 ) {
            error() << "scan lines of image data are not 32bit aligned, QT will not be able to handle that" << std::endl;
            return false;
        }
631
    } else if (glFormat == GL_RGBA || glFormat == GL_BGRA) {
Robert Menzel's avatar
Robert Menzel committed
632
633
634
635
636
637
638
        format = QImage::Format_ARGB32;
    } else {
        error() << "unsupported OpenGL format" << std::endl;
    }

    QImage image = QImage( _data->getData(), _data->getWidth(), _data->getHeight(), format );
    return image.save( QString( _filename.c_str() ) );
639
640
}
#endif
Robert Menzel's avatar
Robert Menzel committed
641
642
643

} // OpenGL
} // ACGL