aboutsummaryrefslogtreecommitdiffstats
path: root/tex.c
blob: a24a430677ae417d077cc23e7cd28859d1500b4f (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
43
44
/*
 * Copyright (C) 2018 Tomasz Kramkowski <tk@the-tk.com>
 * SPDX-License-Identifier: MIT
 */
#include <assert.h>
#include <png.h>
#include <stdlib.h>

#include "eprintf.h"
#include "tex.h"

// png2tex: read a PNG and produce an OpenGL texture out of it
GLuint png2tex(FILE *f)
{
	png_image pi = { .version = PNG_IMAGE_VERSION };
	unsigned char *data;
	size_t stride, size;
	GLuint id;

	assert(f != NULL);

	png_image_begin_read_from_stdio(&pi, f);
	pi.format = PNG_FORMAT_RGB;
	stride = sizeof *data * PNG_IMAGE_SAMPLE_CHANNELS(pi.format) * pi.width;
	// OpenGL alignment requirement
	stride = (stride + 3) & ~(size_t)3;
	size = stride * pi.height;
	data = emalloc(size);
	png_image_finish_read(&pi, NULL, data, stride, NULL);

	gl_tex_gen(1, &id);
	gl_tex_bind(GL_TEXTURE_2D, id);
	gl_tex_parami(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	gl_tex_parami(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	gl_tex_parami(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	gl_tex_parami(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	gl_tex_img2d(GL_TEXTURE_2D, 0, GL_SRGB, pi.width, pi.height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
	gl_tex_genmip(GL_TEXTURE_2D);

	free(data);
	png_image_free(&pi);

	return id;
}