]> git.lizzy.rs Git - shadowclad.git/blob - src/engine/tga.c
Add copyright and license notices in source code
[shadowclad.git] / src / engine / tga.c
1 /**
2  * Copyright 2018-2020 Iwo 'Outfrost' Bujkiewicz
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7  */
8
9 #include "tga.h"
10
11 #include <stdio.h>
12 #include <stdlib.h>
13
14 TgaImage* readTga(const char* path) {
15         FILE* tgaFile = fopen(path, "rb");
16         if (tgaFile == NULL) {
17                 return NULL;
18         }
19
20         TgaHeader header;
21
22         if (fread(&header, sizeof(TgaHeader), 1, tgaFile) != 1) {
23                 fclose(tgaFile);
24                 return NULL;
25         }
26
27         GLenum imageFormat;
28         GLint imageComponents;
29
30         switch (header.imageBpp) {
31                 case 32:
32                         imageFormat = GL_BGRA;
33                         imageComponents = GL_RGBA8;
34                         break;
35                 case 24:
36                         imageFormat = GL_BGR;
37                         imageComponents = GL_RGB8;
38                         break;
39                 case 8:
40                         imageFormat = GL_LUMINANCE;
41                         imageComponents = GL_LUMINANCE8;
42                         break;
43                 default:
44                         fclose(tgaFile);
45                         return NULL;
46         }
47
48         unsigned long imageSize = header.imageWidth * header.imageHeight * (header.imageBpp >> 3);
49
50         GLbyte* bytes = malloc(imageSize * sizeof(GLbyte));
51         if (bytes == NULL) {
52                 fclose(tgaFile);
53                 return NULL;
54         }
55
56         if (fread(bytes, imageSize, 1, tgaFile) != 1) {
57                 free(bytes);
58                 fclose(tgaFile);
59                 return NULL;
60         }
61
62         fclose(tgaFile);
63
64         TgaImage* image = malloc(sizeof(TgaImage));
65         if (image == NULL) {
66                 return NULL;
67         }
68
69         (*image).header = header;
70         (*image).imageFormat = imageFormat;
71         (*image).imageComponents = imageComponents;
72         (*image).bytes = bytes;
73
74         return image;
75 }