summaryrefslogtreecommitdiff
path: root/src/texture.c
blob: d365e3b0fc84e91585bb7febea6e202febaa2e91 (plain)
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
#include "stb_image.h"
#include "texture.h"
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

int
texture_init(Texture *this, const char *img_path)
{
	glGenTextures(1, &this->id);
	if (this->id == 0) {
		fprintf(stderr, "glGenTextures failed\n");
		return -1;
	}

	stbi_set_flip_vertically_on_load(1);
	int width, height, nb_chans;
	uint8_t *const data = stbi_load(img_path, &width, &height, &nb_chans, 3);
	if (data == NULL) {
		fprintf(stderr, "failed to load image '%s'\n", img_path);
		texture_deinit(this);
		return -1;
	}

	glBindTexture(GL_TEXTURE_2D, this->id);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height,
	             0, GL_RGB, GL_UNSIGNED_BYTE, data);
	stbi_image_free(data);

	glGenerateMipmap(GL_TEXTURE_2D);

	return 0;
}

void
texture_deinit(Texture *this)
{
	if (this->id) {
		glDeleteTextures(1, &this->id);
		this->id = 0;
	}
}