-
Notifications
You must be signed in to change notification settings - Fork 271
/
Copy pathimageutils.cpp
2367 lines (1956 loc) · 63.4 KB
/
imageutils.cpp
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
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
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
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// NOTE: To make use of this file, g_pFullFileSystem must be defined, or you can modify
// this source to take an IFileSystem * as input.
//
//=======================================================================================//
// @note Tom Bui: we need to use fopen below in the jpeg code, so we can't have this on...
#ifdef PROTECTED_THINGS_ENABLE
#if !defined( POSIX )
#undef fopen
#endif // POSIX
#endif
#if defined( WIN32 ) && !defined( _X360 )
#include <windows.h> // SRC only!!
#elif defined( POSIX )
#include <stdio.h>
#include <sys/stat.h>
#ifdef OSX
#include <copyfile.h>
#endif
#endif
#include "imageutils.h"
#include "filesystem.h"
#include "utlbuffer.h"
#include "bitmap/bitmap.h"
#include "vtf/vtf.h"
// clang3 on OSX folks the attribute into the prototype, causing a compile failure
// filed radar bug 10397783
#if ( __clang_major__ == 3 )
#include <setjmp.h>
extern void longjmp( jmp_buf, int ) __attribute__((noreturn));
#endif
#ifdef ENGINE_DLL
#include "common.h"
#elif CLIENT_DLL
// @note Tom Bui: instead of forcing the project to include EngineInterface.h...
#include "cdll_int.h"
// engine interface singleton accessors
extern IVEngineClient *engine;
extern class IGameUIFuncs *gameuifuncs;
extern class IEngineSound *enginesound;
extern class IMatchmaking *matchmaking;
extern class IXboxSystem *xboxsystem;
extern class IAchievementMgr *achievementmgr;
extern class CSteamAPIContext *steamapicontext;
#elif REPLAY_DLL
#include "replay/ienginereplay.h"
extern IEngineReplay *g_pEngine;
#elif ENGINE_DLL
#include "EngineInterface.h"
#elif UTILS
// OwO
#else
#include "cdll_int.h"
extern IVEngineClient *engine;
#endif
// use the JPEGLIB_USE_STDIO define so that we can read in jpeg's from outside the game directory tree.
#define JPEGLIB_USE_STDIO
#if ANDROID
#include "android/jpeglib/jpeglib.h"
#elif defined WIN32
#include "jpeglib/jpeglib.h"
#else
#include <jpeglib.h>
#endif
#undef JPEGLIB_USE_STDIO
#if HAVE_PNG
#if ANDROID || WIN32
#include "libpng/png.h"
#else
#include <png.h>
#endif
#endif
#include <setjmp.h>
#include "bitmap/tgawriter.h"
#include "ivtex.h"
#ifdef WIN32
#include <io.h>
#endif
#ifdef OSX
#include <copyfile.h>
#endif
#ifndef WIN32
#define DeleteFile(s) remove(s)
#endif
#if defined( _X360 )
#include "xbox/xbox_win32stubs.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
#if HAVE_JPEG
struct ValveJpegErrorHandler_t
{
// The default manager
struct jpeg_error_mgr m_Base;
// For handling any errors
jmp_buf m_ErrorContext;
};
#define JPEG_OUTPUT_BUF_SIZE 4096
struct JPEGDestinationManager_t
{
struct jpeg_destination_mgr pub; // public fields
CUtlBuffer *pBuffer; // target/final buffer
byte *buffer; // start of temp buffer
};
//-----------------------------------------------------------------------------
// Purpose: We'll override the default error handler so we can deal with errors without having to exit the engine
//-----------------------------------------------------------------------------
static void ValveJpegErrorHandler( j_common_ptr cinfo )
{
ValveJpegErrorHandler_t *pError = reinterpret_cast< ValveJpegErrorHandler_t * >( cinfo->err );
char buffer[ JMSG_LENGTH_MAX ];
/* Create the message */
( *cinfo->err->format_message )( cinfo, buffer );
Warning( "%s\n", buffer );
// Bail
longjmp( pError->m_ErrorContext, 1 );
}
#endif
// convert the JPEG file given to a TGA file at the given output path.
ConversionErrorType ImgUtl_ConvertJPEGToTGA( const char *jpegpath, const char *tgaPath, bool bRequirePowerOfTwo )
{
#if !defined( _X360 ) && HAVE_JPEG
//
// !FIXME! This really probably should use ImgUtl_ReadJPEGAsRGBA, to avoid duplicated code.
//
struct jpeg_decompress_struct jpegInfo;
struct ValveJpegErrorHandler_t jerr;
JSAMPROW row_pointer[1];
int row_stride;
int cur_row = 0;
// image attributes
int image_height;
int image_width;
// open the jpeg image file.
FILE *infile = fopen(jpegpath, "rb");
if (infile == NULL)
{
return CE_CANT_OPEN_SOURCE_FILE;
}
// setup error to print to stderr.
jpegInfo.err = jpeg_std_error(&jerr.m_Base);
jpegInfo.err->error_exit = &ValveJpegErrorHandler;
// create the decompress struct.
jpeg_create_decompress(&jpegInfo);
if ( setjmp( jerr.m_ErrorContext ) )
{
// Get here if there is any error
jpeg_destroy_decompress( &jpegInfo );
fclose(infile);
return CE_ERROR_PARSING_SOURCE;
}
jpeg_stdio_src(&jpegInfo, infile);
// read in the jpeg header and make sure that's all good.
if (jpeg_read_header(&jpegInfo, TRUE) != JPEG_HEADER_OK)
{
fclose(infile);
return CE_ERROR_PARSING_SOURCE;
}
// start the decompress with the jpeg engine.
if ( !jpeg_start_decompress(&jpegInfo) )
{
jpeg_destroy_decompress(&jpegInfo);
fclose(infile);
return CE_ERROR_PARSING_SOURCE;
}
// Check for valid width and height (ie. power of 2 and print out an error and exit if not).
if ( ( bRequirePowerOfTwo && ( !IsPowerOfTwo(jpegInfo.image_height) || !IsPowerOfTwo(jpegInfo.image_width) ) )
|| jpegInfo.output_components != 3 )
{
jpeg_destroy_decompress(&jpegInfo);
fclose( infile );
return CE_SOURCE_FILE_SIZE_NOT_SUPPORTED;
}
// now that we've started the decompress with the jpeg lib, we have the attributes of the
// image ready to be read out of the decompress struct.
row_stride = jpegInfo.output_width * jpegInfo.output_components;
image_height = jpegInfo.image_height;
image_width = jpegInfo.image_width;
int mem_required = jpegInfo.image_height * jpegInfo.image_width * jpegInfo.output_components;
// allocate the memory to read the image data into.
unsigned char *buf = (unsigned char *)malloc(mem_required);
if (buf == NULL)
{
jpeg_destroy_decompress(&jpegInfo);
fclose(infile);
return CE_MEMORY_ERROR;
}
// read in all the scan lines of the image into our image data buffer.
bool working = true;
while (working && (jpegInfo.output_scanline < jpegInfo.output_height))
{
row_pointer[0] = &(buf[cur_row * row_stride]);
if ( !jpeg_read_scanlines(&jpegInfo, row_pointer, 1) )
{
working = false;
}
++cur_row;
}
if (!working)
{
free(buf);
jpeg_destroy_decompress(&jpegInfo);
fclose(infile);
return CE_ERROR_PARSING_SOURCE;
}
jpeg_finish_decompress(&jpegInfo);
fclose(infile);
// ok, at this point we have read in the JPEG image to our buffer, now we need to write it out as a TGA file.
CUtlBuffer outBuf;
bool bRetVal = TGAWriter::WriteToBuffer( buf, outBuf, image_width, image_height, IMAGE_FORMAT_RGB888, IMAGE_FORMAT_RGB888 );
if ( bRetVal )
{
if ( !g_pFullFileSystem->WriteFile( tgaPath, NULL, outBuf ) )
{
bRetVal = false;
}
}
free(buf);
return bRetVal ? CE_SUCCESS : CE_ERROR_WRITING_OUTPUT_FILE;
#else
return CE_SOURCE_FILE_FORMAT_NOT_SUPPORTED;
#endif
}
// convert the bmp file given to a TGA file at the given destination path.
ConversionErrorType ImgUtl_ConvertBMPToTGA(const char *bmpPath, const char *tgaPath)
{
if ( !IsPC() )
return CE_SOURCE_FILE_FORMAT_NOT_SUPPORTED;
#ifdef WIN32
int nWidth, nHeight;
ConversionErrorType result;
unsigned char *pBufRGBA = ImgUtl_ReadBMPAsRGBA( bmpPath, nWidth, nHeight, result );
if ( result != CE_SUCCESS)
{
Assert( !pBufRGBA );
free( pBufRGBA );
return result;
}
Assert( pBufRGBA );
// write out the TGA file using the RGB data buffer.
CUtlBuffer outBuf;
bool retval = TGAWriter::WriteToBuffer(pBufRGBA, outBuf, nWidth, nHeight, IMAGE_FORMAT_RGBA8888, IMAGE_FORMAT_RGB888);
free( pBufRGBA );
if ( retval )
{
if ( !g_pFullFileSystem->WriteFile( tgaPath, NULL, outBuf ) )
{
retval = false;
}
}
return retval ? CE_SUCCESS : CE_ERROR_WRITING_OUTPUT_FILE;
#else // WIN32
return CE_SOURCE_FILE_FORMAT_NOT_SUPPORTED;
#endif
}
unsigned char *ImgUtl_ReadVTFAsRGBA( const char *vtfPath, int &width, int &height, ConversionErrorType &errcode )
{
// Just load the whole file into a memory buffer
CUtlBuffer bufFileContents;
if ( !g_pFullFileSystem->ReadFile( vtfPath, NULL, bufFileContents ) )
{
errcode = CE_CANT_OPEN_SOURCE_FILE;
return NULL;
}
IVTFTexture *pVTFTexture = CreateVTFTexture();
if ( !pVTFTexture->Unserialize( bufFileContents ) )
{
DestroyVTFTexture( pVTFTexture );
errcode = CE_ERROR_PARSING_SOURCE;
return NULL;
}
width = pVTFTexture->Width();
height = pVTFTexture->Height();
pVTFTexture->ConvertImageFormat( IMAGE_FORMAT_RGBA8888, false );
int nMemSize = ImageLoader::GetMemRequired( width, height, 1, IMAGE_FORMAT_RGBA8888, false );
unsigned char *pMemImage = (unsigned char *)malloc(nMemSize);
if ( pMemImage == NULL )
{
DestroyVTFTexture( pVTFTexture );
errcode = CE_MEMORY_ERROR;
return NULL;
}
Q_memcpy( pMemImage, pVTFTexture->ImageData(), nMemSize );
DestroyVTFTexture( pVTFTexture );
errcode = CE_SUCCESS;
return pMemImage;
}
// read a TGA header from the current point in the file stream.
static void ImgUtl_ReadTGAHeader(FILE *infile, TGAHeader &header)
{
if (infile == NULL)
{
return;
}
fread(&header.identsize, sizeof(header.identsize), 1, infile);
fread(&header.colourmaptype, sizeof(header.colourmaptype), 1, infile);
fread(&header.imagetype, sizeof(header.imagetype), 1, infile);
fread(&header.colourmapstart, sizeof(header.colourmapstart), 1, infile);
fread(&header.colourmaplength, sizeof(header.colourmaplength), 1, infile);
fread(&header.colourmapbits, sizeof(header.colourmapbits), 1, infile);
fread(&header.xstart, sizeof(header.xstart), 1, infile);
fread(&header.ystart, sizeof(header.ystart), 1, infile);
fread(&header.width, sizeof(header.width), 1, infile);
fread(&header.height, sizeof(header.height), 1, infile);
fread(&header.bits, sizeof(header.bits), 1, infile);
fread(&header.descriptor, sizeof(header.descriptor), 1, infile);
}
// write a TGA header to the current point in the file stream.
static void WriteTGAHeader(FILE *outfile, TGAHeader &header)
{
if (outfile == NULL)
{
return;
}
fwrite(&header.identsize, sizeof(header.identsize), 1, outfile);
fwrite(&header.colourmaptype, sizeof(header.colourmaptype), 1, outfile);
fwrite(&header.imagetype, sizeof(header.imagetype), 1, outfile);
fwrite(&header.colourmapstart, sizeof(header.colourmapstart), 1, outfile);
fwrite(&header.colourmaplength, sizeof(header.colourmaplength), 1, outfile);
fwrite(&header.colourmapbits, sizeof(header.colourmapbits), 1, outfile);
fwrite(&header.xstart, sizeof(header.xstart), 1, outfile);
fwrite(&header.ystart, sizeof(header.ystart), 1, outfile);
fwrite(&header.width, sizeof(header.width), 1, outfile);
fwrite(&header.height, sizeof(header.height), 1, outfile);
fwrite(&header.bits, sizeof(header.bits), 1, outfile);
fwrite(&header.descriptor, sizeof(header.descriptor), 1, outfile);
}
// reads in a TGA file and converts it to 32 bit RGBA color values in a memory buffer.
unsigned char * ImgUtl_ReadTGAAsRGBA(const char *tgaPath, int &width, int &height, ConversionErrorType &errcode, TGAHeader &tgaHeader )
{
FILE *tgaFile = fopen(tgaPath, "rb");
if (tgaFile == NULL)
{
errcode = CE_CANT_OPEN_SOURCE_FILE;
return NULL;
}
// read header for TGA file.
ImgUtl_ReadTGAHeader(tgaFile, tgaHeader);
if (
( tgaHeader.imagetype != 2 ) // image type 2 is uncompressed RGB, other types not supported.
|| ( tgaHeader.descriptor & 0x10 ) // Origin on righthand side (flipped horizontally from common sense) --- nobody ever uses this
|| ( tgaHeader.bits != 24 && tgaHeader.bits != 32 ) // Must be 24- ot 32-bit
)
{
fclose(tgaFile);
errcode = CE_SOURCE_FILE_TGA_FORMAT_NOT_SUPPORTED;
return NULL;
}
int tgaDataSize = tgaHeader.width * tgaHeader.height * tgaHeader.bits / 8;
unsigned char *tgaData = (unsigned char *)malloc(tgaDataSize);
if (tgaData == NULL)
{
fclose(tgaFile);
errcode = CE_MEMORY_ERROR;
return NULL;
}
fread(tgaData, 1, tgaDataSize, tgaFile);
fclose(tgaFile);
width = tgaHeader.width;
height = tgaHeader.height;
int numPixels = tgaHeader.width * tgaHeader.height;
if (tgaHeader.bits == 24)
{
// image needs to be converted to a 32-bit image.
unsigned char *retBuf = (unsigned char *)malloc(numPixels * 4);
if (retBuf == NULL)
{
free(tgaData);
errcode = CE_MEMORY_ERROR;
return NULL;
}
// convert from BGR to RGBA color format.
for (int index = 0; index < numPixels; ++index)
{
retBuf[index * 4] = tgaData[index * 3 + 2];
retBuf[index * 4 + 1] = tgaData[index * 3 + 1];
retBuf[index * 4 + 2] = tgaData[index * 3];
retBuf[index * 4 + 3] = 0xff;
}
free(tgaData);
tgaData = retBuf;
tgaHeader.bits = 32;
}
else if (tgaHeader.bits == 32)
{
// Swap blue and red to convert BGR -> RGB
for (int index = 0; index < numPixels; ++index)
{
V_swap( tgaData[index*4], tgaData[index*4 + 2] );
}
}
// Flip image vertically if necessary
if ( !( tgaHeader.descriptor & 0x20 ) )
{
int y0 = 0;
int y1 = height-1;
int iStride = width*4;
while ( y0 < y1 )
{
unsigned char *ptr0 = tgaData + y0*iStride;
unsigned char *ptr1 = tgaData + y1*iStride;
for ( int i = 0 ; i < iStride ; ++i )
{
V_swap( ptr0[i], ptr1[i] );
}
++y0;
--y1;
}
tgaHeader.descriptor |= 0x20;
}
errcode = CE_SUCCESS;
return tgaData;
}
unsigned char *ImgUtl_ReadJPEGAsRGBA( const char *jpegPath, int &width, int &height, ConversionErrorType &errcode )
{
#if !defined( _X360 ) && HAVE_JPEG
struct jpeg_decompress_struct jpegInfo;
struct ValveJpegErrorHandler_t jerr;
JSAMPROW row_pointer[1];
int row_stride;
int cur_row = 0;
// image attributes
int image_height;
int image_width;
// open the jpeg image file.
FILE *infile = fopen(jpegPath, "rb");
if (infile == NULL)
{
errcode = CE_CANT_OPEN_SOURCE_FILE;
return NULL;
}
//CJpegSourceMgr src;
//FileHandle_t fileHandle = g_pFullFileSystem->Open( jpegPath, "rb" );
//if ( fileHandle == FILESYSTEM_INVALID_HANDLE )
//{
// errcode = CE_CANT_OPEN_SOURCE_FILE;
// return NULL;
//}
//if ( !src.Init( g_pFullFileSystem, fileHandle ) ) {
// errcode = CE_CANT_OPEN_SOURCE_FILE;
// g_pFullFileSystem->Close( fileHandle );
// return NULL;
//}
// setup error to print to stderr.
memset( &jpegInfo, 0, sizeof( jpegInfo ) );
jpegInfo.err = jpeg_std_error(&jerr.m_Base);
jpegInfo.err->error_exit = &ValveJpegErrorHandler;
// create the decompress struct.
jpeg_create_decompress(&jpegInfo);
if ( setjmp( jerr.m_ErrorContext ) )
{
// Get here if there is any error
jpeg_destroy_decompress( &jpegInfo );
fclose( infile );
//g_pFullFileSystem->Close( fileHandle );
errcode = CE_ERROR_PARSING_SOURCE;
return NULL;
}
jpeg_stdio_src(&jpegInfo, infile);
//jpegInfo.src = &src;
// read in the jpeg header and make sure that's all good.
if (jpeg_read_header(&jpegInfo, TRUE) != JPEG_HEADER_OK)
{
fclose( infile );
//g_pFullFileSystem->Close( fileHandle );
errcode = CE_ERROR_PARSING_SOURCE;
return NULL;
}
// start the decompress with the jpeg engine.
if ( !jpeg_start_decompress(&jpegInfo) )
{
jpeg_destroy_decompress(&jpegInfo);
fclose( infile );
//g_pFullFileSystem->Close( fileHandle );
errcode = CE_ERROR_PARSING_SOURCE;
return NULL;
}
// We only support 24-bit JPEG's
if ( jpegInfo.out_color_space != JCS_RGB || jpegInfo.output_components != 3 )
{
jpeg_destroy_decompress(&jpegInfo);
fclose( infile );
//g_pFullFileSystem->Close( fileHandle );
errcode = CE_SOURCE_FILE_SIZE_NOT_SUPPORTED;
return NULL;
}
// now that we've started the decompress with the jpeg lib, we have the attributes of the
// image ready to be read out of the decompress struct.
row_stride = jpegInfo.output_width * 4;
image_height = jpegInfo.image_height;
image_width = jpegInfo.image_width;
int mem_required = jpegInfo.image_height * row_stride;
// allocate the memory to read the image data into.
unsigned char *buf = (unsigned char *)malloc(mem_required);
if (buf == NULL)
{
jpeg_destroy_decompress(&jpegInfo);
fclose( infile );
//g_pFullFileSystem->Close( fileHandle );
errcode = CE_MEMORY_ERROR;
return NULL;
}
// read in all the scan lines of the image into our image data buffer.
bool working = true;
while (working && (jpegInfo.output_scanline < jpegInfo.output_height))
{
unsigned char *pRow = &(buf[cur_row * row_stride]);
row_pointer[0] = pRow;
if ( !jpeg_read_scanlines(&jpegInfo, row_pointer, 1) )
{
working = false;
}
// Expand the row RGB -> RGBA
for ( int x = image_width-1 ; x >= 0 ; --x )
{
pRow[x*4+3] = 0xff;
pRow[x*4+2] = pRow[x*3+2];
pRow[x*4+1] = pRow[x*3+1];
pRow[x*4] = pRow[x*3];
}
++cur_row;
}
// Clean up
fclose( infile );
//g_pFullFileSystem->Close( fileHandle );
jpeg_destroy_decompress(&jpegInfo);
// Check success status
if (!working)
{
free(buf);
errcode = CE_ERROR_PARSING_SOURCE;
return NULL;
}
// OK!
width = image_width;
height = image_height;
errcode = CE_SUCCESS;
return buf;
#else
errcode = CE_SOURCE_FILE_FORMAT_NOT_SUPPORTED;
return NULL;
#endif
}
#if HAVE_PNG
static void ReadPNGData( png_structp png_ptr, png_bytep outBytes, png_size_t byteCountToRead )
{
// Cast pointer
CUtlBuffer *pBuf = (CUtlBuffer *)png_get_io_ptr( png_ptr );
Assert( pBuf );
// Check for IO error
if ( pBuf->TellGet() + (int)byteCountToRead > pBuf->TellPut() )
{
// Attempt to read past the end of the buffer.
// Use longjmp to report the error
png_longjmp( png_ptr, 1 );
}
// Read the bytes
pBuf->Get( outBytes, byteCountToRead );
}
#endif
unsigned char *ImgUtl_ReadPNGAsRGBA( const char *pngPath, int &width, int &height, ConversionErrorType &errcode )
{
#if !defined( _X360 ) && HAVE_PNG
// Just load the whole file into a memory buffer
CUtlBuffer bufFileContents;
#if UTILS
static char buf[8192];
FILE *readfile = fopen(pngPath, "rb");
if( !readfile )
{
errcode = CE_CANT_OPEN_SOURCE_FILE;
return NULL;
}
size_t size;
while( ( size = fread(buf, 1, sizeof(buf), readfile ) ) > 0 )
bufFileContents.Put( buf, size );
// Load it
return ImgUtl_ReadPNGAsRGBAFromBuffer( bufFileContents, width, height, errcode );
#else
if ( !g_pFullFileSystem->ReadFile( pngPath, NULL, bufFileContents ) )
{
errcode = CE_CANT_OPEN_SOURCE_FILE;
return NULL;
}
#endif
// Load it
return ImgUtl_ReadPNGAsRGBAFromBuffer( bufFileContents, width, height, errcode );
#else
errcode = CE_SOURCE_FILE_FORMAT_NOT_SUPPORTED;
return NULL;
#endif
}
unsigned char *ImgUtl_ReadPNGAsRGBAFromBuffer( CUtlBuffer &buffer, int &width, int &height, ConversionErrorType &errcode )
{
#if !defined( _X360 ) && HAVE_PNG
png_const_bytep pngData = (png_const_bytep)buffer.Base();
if (png_sig_cmp( pngData, 0, 8))
{
errcode = CE_ERROR_PARSING_SOURCE;
return NULL;
}
png_structp png_ptr = NULL;
png_infop info_ptr = NULL;
/* could pass pointers to user-defined error handlers instead of NULLs: */
png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL );
if (!png_ptr)
{
errcode = CE_MEMORY_ERROR;
return NULL;
}
unsigned char *pResultData = NULL;
png_bytepp row_pointers = NULL;
info_ptr = png_create_info_struct( png_ptr );
if ( !info_ptr )
{
errcode = CE_MEMORY_ERROR;
fail:
png_destroy_read_struct( &png_ptr, &info_ptr, NULL );
if ( row_pointers )
{
free( row_pointers );
}
if ( pResultData )
{
free( pResultData );
}
return NULL;
}
/* setjmp() must be called in every function that calls a PNG-reading
* libpng function */
if ( setjmp( png_jmpbuf(png_ptr) ) )
{
errcode = CE_ERROR_PARSING_SOURCE;
goto fail;
}
png_set_read_fn( png_ptr, &buffer, ReadPNGData );
png_read_info( png_ptr, info_ptr ); /* read all PNG info up to image data */
/* alternatively, could make separate calls to png_get_image_width(),
* etc., but want bit_depth and color_type for later [don't care about
* compression_type and filter_type => NULLs] */
int bit_depth;
int color_type;
uint32 png_width;
uint32 png_height;
png_get_IHDR( png_ptr, info_ptr, &png_width, &png_height, &bit_depth, &color_type, NULL, NULL, NULL );
width = png_width;
height = png_height;
png_uint_32 rowbytes;
/* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,
* transparency chunks to full alpha channel; strip 16-bit-per-sample
* images to 8 bits per sample; and convert grayscale to RGB[A] */
if (color_type == PNG_COLOR_TYPE_PALETTE)
png_set_expand( png_ptr );
if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
png_set_expand( png_ptr );
if (png_get_valid( png_ptr, info_ptr, PNG_INFO_tRNS ) )
png_set_expand( png_ptr );
if (bit_depth == 16)
png_set_strip_16( png_ptr );
if (color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb( png_ptr );
// Force in an alpha channel
if ( !( color_type & PNG_COLOR_MASK_ALPHA ) )
{
png_set_add_alpha(png_ptr, 255, PNG_FILLER_AFTER);
}
/*
double gamma;
if (png_get_gAMA(png_ptr, info_ptr, &gamma))
png_set_gamma(png_ptr, display_exponent, gamma);
*/
/* all transformations have been registered; now update info_ptr data,
* get rowbytes and channels, and allocate image memory */
png_read_update_info( png_ptr, info_ptr );
rowbytes = png_get_rowbytes( png_ptr, info_ptr );
png_byte channels = (int)png_get_channels( png_ptr, info_ptr );
if ( channels != 4 )
{
Assert( channels == 4 );
errcode = CE_SOURCE_FILE_FORMAT_NOT_SUPPORTED;
goto fail;
}
row_pointers = (png_bytepp)malloc( height*sizeof(png_bytep) );
pResultData = (unsigned char *)malloc( rowbytes*height );
if ( row_pointers == NULL || pResultData == NULL )
{
errcode = CE_MEMORY_ERROR;
goto fail;
}
/* set the individual row_pointers to point at the correct offsets */
for ( int i = 0; i < height; ++i)
row_pointers[i] = pResultData + i*rowbytes;
/* now we can go ahead and just read the whole image */
png_read_image( png_ptr, row_pointers );
png_read_end(png_ptr, NULL);
free( row_pointers );
row_pointers = NULL;
// Clean up
png_destroy_read_struct( &png_ptr, &info_ptr, NULL );
// OK!
width = png_width;
height = png_height;
errcode = CE_SUCCESS;
return pResultData;
#else
errcode = CE_SOURCE_FILE_FORMAT_NOT_SUPPORTED;
return NULL;
#endif
}
unsigned char *ImgUtl_ReadBMPAsRGBA( const char *bmpPath, int &width, int &height, ConversionErrorType &errcode )
{
#ifdef WIN32
// Load up bitmap
HBITMAP hBitmap = (HBITMAP)LoadImage(NULL, bmpPath, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_LOADFROMFILE | LR_DEFAULTSIZE);
// Handle failure
if ( hBitmap == NULL)
{
// !KLUDGE! Try to detect what went wrong
FILE *fp = fopen( bmpPath, "rb" );
if (fp == NULL)
{
errcode = CE_CANT_OPEN_SOURCE_FILE;
}
else
{
errcode = CE_ERROR_PARSING_SOURCE;
}
return NULL;
}
BITMAP bitmap;
GetObject(hBitmap, sizeof(bitmap), &bitmap);
BITMAPINFO *bitmapInfo;
bool bUseColorTable = false;
if (bitmap.bmBitsPixel == 24 || bitmap.bmBitsPixel == 32)
{
bitmapInfo = (BITMAPINFO *)malloc(sizeof(BITMAPINFO));
}
else if (bitmap.bmBitsPixel == 8 || bitmap.bmBitsPixel == 4 || bitmap.bmBitsPixel == 1)
{
int colorsUsed = 1 << bitmap.bmBitsPixel;
bitmapInfo = (BITMAPINFO *)malloc(colorsUsed * sizeof(RGBQUAD) + sizeof(BITMAPINFO));
bUseColorTable = true;
}
else
{
DeleteObject(hBitmap);
errcode = CE_SOURCE_FILE_BMP_FORMAT_NOT_SUPPORTED;
return NULL;
}
memset(bitmapInfo, 0, sizeof(BITMAPINFO));
bitmapInfo->bmiHeader.biSize = sizeof(bitmapInfo->bmiHeader);
if (bUseColorTable)
{
bitmapInfo->bmiHeader.biBitCount = bitmap.bmBitsPixel; // need to specify the bits per pixel so GDI will generate a color table for us.
}
HDC dc = CreateCompatibleDC(NULL);
int retcode = GetDIBits(dc, hBitmap, 0, bitmap.bmHeight, NULL, bitmapInfo, DIB_RGB_COLORS);
DeleteDC(dc);
if (retcode == 0)
{
// error getting the bitmap info for some reason.
free(bitmapInfo);
errcode = CE_SOURCE_FILE_BMP_FORMAT_NOT_SUPPORTED;
return NULL;
}
int nDestStride = 4 * bitmap.bmWidth;
int mem_required = nDestStride * bitmap.bmHeight; // mem required for copying the data out into RGBA format.
unsigned char *buf = (unsigned char *)malloc(mem_required);
if (buf == NULL)
{
free(bitmapInfo);
errcode = CE_MEMORY_ERROR;
return NULL;
}
if (bitmapInfo->bmiHeader.biBitCount == 32)
{
for (int y = 0; y < bitmap.bmHeight; ++y)
{
unsigned char *pDest = buf + nDestStride * ( ( bitmap.bmHeight - 1 ) - y ); // BMPs are stored upside down
const unsigned char *pSrc = (unsigned char *)(bitmap.bmBits) + (y * bitmap.bmWidthBytes);
for (int x = 0; x < bitmap.bmWidth; ++x)
{
// Swap BGR -> RGB while copying data
pDest[0] = pSrc[2]; // R
pDest[1] = pSrc[1]; // G
pDest[2] = pSrc[0]; // B
pDest[3] = pSrc[3]; // A
pSrc += 4;
pDest += 4;
}
}
}
else if (bitmapInfo->bmiHeader.biBitCount == 24)
{
for (int y = 0; y < bitmap.bmHeight; ++y)
{
unsigned char *pDest = buf + nDestStride * ( ( bitmap.bmHeight - 1 ) - y ); // BMPs are stored upside down
const unsigned char *pSrc = (unsigned char *)(bitmap.bmBits) + (y * bitmap.bmWidthBytes);
for (int x = 0; x < bitmap.bmWidth; ++x)
{
// Swap BGR -> RGB while copying data
pDest[0] = pSrc[2]; // R
pDest[1] = pSrc[1]; // G
pDest[2] = pSrc[0]; // B
pDest[3] = 0xff; // A
pSrc += 3;
pDest += 4;
}
}
}
else if (bitmapInfo->bmiHeader.biBitCount == 8)
{
// 8-bit 256 color bitmap.
for (int y = 0; y < bitmap.bmHeight; ++y)
{
unsigned char *pDest = buf + nDestStride * ( ( bitmap.bmHeight - 1 ) - y ); // BMPs are stored upside down
const unsigned char *pSrc = (unsigned char *)(bitmap.bmBits) + (y * bitmap.bmWidthBytes);
for (int x = 0; x < bitmap.bmWidth; ++x)