aboutsummaryrefslogtreecommitdiffstats
path: root/mtl.c
blob: dc74e01e4437c432355aa6ed452953d9f960955f (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
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
/*
 * Copyright (C) 2018 Tomasz Kramkowski <tk@the-tk.com>
 * SPDX-License-Identifier: MIT
 */
#include <assert.h>
#include <stdio.h>
#include <string.h>

#include "ensize.h"
#include "eprintf.h"
#include "mtl.h"
#include "tex.h"

struct mtl {
	char name[50];
	GLuint diff;
	GLuint spec;
};

static struct mtl *mtls;
static int lmtls;
static size_t nmtls;

GLuint tex_file(const char *name, const char *type)
{
	char loc[100];
	GLuint ret;
	FILE *f;

	snprintf(loc, sizeof loc, "assets/%s.%s.png", name, type);
	f = fopen(loc, "rb");
	if (f == NULL)
		eprintf("Could not open '%s':", loc);
	ret = png2tex(f);
	fclose(f);

	return ret;
}

int mtl_load(char *name)
{
	struct mtl *m;

	for (int i = 0; i < lmtls; i++)
		if (strcmp(mtls[i].name, name) == 0)
			return i;

	mtls = ENSIZE(mtls, lmtls + 1, &nmtls, 16);
	m = &mtls[lmtls];

	snprintf(m->name, sizeof m->name, "%s", name);

	m->diff = tex_file(name, "diff");
	m->spec = tex_file(name, "spec");

	return lmtls++;
}

void mtl_use(int mtl)
{
	assert(mtl < lmtls);

	// TODO: Blank textures or something
	if (mtl < 0)
		return;

	gl_tex_active(GL_TEXTURE0);
	gl_tex_bind(GL_TEXTURE_2D, mtls[mtl].diff);
	gl_tex_active(GL_TEXTURE1);
	gl_tex_bind(GL_TEXTURE_2D, mtls[mtl].spec);
}