-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbmp_loader.cpp
84 lines (68 loc) · 1.95 KB
/
bmp_loader.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
#include <stdlib.h>
#include <stdio.h>
// windows.h must be included before GL headers
#ifdef _MSC_VER
#include <windows.h>
#endif
#include <GL/gl.h>
#ifndef GL_BGR
#include <GL/glext.h>
#endif
/*
* This code is partially taken from http://www.opengl-tutorial.org/beginners-tutorials/tutorial-5-a-textured-cube/
* Structs are taken from Wikipedia
*/
#pragma pack(push, 1)
typedef struct {
GLushort type;
GLuint size;
GLushort reserved1;
GLushort reserved2;
GLuint offset;
} BMPFileHeader;
typedef struct {
GLuint size;
GLint width;
GLint height;
GLushort planes;
GLushort bitCount;
GLuint compression;
GLuint sizeImage;
GLint XPelsPerMeter;
GLint YPelsPerMeter;
GLuint clrUsed;
GLuint clrImportant;
} BMPInfoHeader;
#pragma pack(pop)
GLuint loadBMPTexture(const char *filename) {
FILE *bmp = fopen(filename, "rb");
if (!bmp) {
perror("Cannot open image file");
return 0;
}
BMPFileHeader hdr;
BMPInfoHeader info;
fread(&hdr, 1, sizeof(hdr), bmp);
fread(&info, 1, sizeof(info), bmp);
if (info.width == 0 || info.height == 0 || hdr.offset == 0 || info.sizeImage == 0) {
fprintf(stderr, "Malformed BMP file\n");
fclose(bmp);
return 0;
}
if (info.bitCount != 24 || info.compression != 0) { // 0 is BI_RGB, uncompressed image
fprintf(stderr, "Only 24-bit uncompressed BMP's are supported\n");
fclose(bmp);
return 0;
}
GLubyte *data = (GLubyte*) malloc(info.sizeImage);
fread(data, 1, info.sizeImage, bmp);
fclose(bmp);
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, info.width, info.height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
free(data);
return texture;
}