summary refs log tree commit diff
path: root/src/Textures.cpp
blob: 9e22c875e97599aa276424ff5de977b10cf07c90 (plain) (blame)
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
// Texture loader implementation
// Copyright (C) 2021  Nguyễn Gia Phong
//
// This file is part of Black Shades.
//
// Black Shades is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Black Shades is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Black Shades.  If not, see <https://www.gnu.org/licenses/>.

#include <stdio.h>

#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
#include <GL/glu.h>

#include "Textures.h"

GLuint loadTexture(const char* filename_, GLenum minFilter,
	GLenum magFilter, bool mipmaps)
{
	// TODO: get rid of the :Data: thing
	char filename[1024];
	strcpy(filename, filename_+1);
	while (true) {
		char *c = strchr(filename, ':');
		if (!c) break;
		*c = '/';
	}

	int req_format = STBI_rgb_alpha;
	int width, height, orig_format;
	unsigned char* data = stbi_load(filename, &width, &height,
		&orig_format, req_format);
	if (data == nullptr) {
		fprintf(stderr, "Loading image failed: %s\n",
			stbi_failure_reason());
		return 0;
	}

	GLuint tex = 0;
	glGenTextures(1, &tex);
	glBindTexture(GL_TEXTURE_2D, tex);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);

	GLint internal_format;
	GLenum pixel_format;
	if (req_format == STBI_rgb) {
		internal_format = 3;
		pixel_format = GL_RGB;
	} else { // STBI_rgb_alpha (RGBA)
		internal_format = 4;
		pixel_format = GL_RGBA;
	}

	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0,
		pixel_format, GL_UNSIGNED_BYTE, data);
	if (mipmaps)
		gluBuild2DMipmaps(GL_TEXTURE_2D, internal_format, width, height,
			pixel_format, GL_UNSIGNED_BYTE, data);

	stbi_image_free(data);
	return tex;
}