aboutsummaryrefslogtreecommitdiff
path: root/assets.c
blob: 0b1f66c021ed6f0a81805d7dd33f51549a89870e (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
72
73
74
75
76
77
78
79
80
81
#include "all.h"

#include <stdio.h>
#include <string.h>
#include <ctype.h>

static array(CachedTexture) texture_cache;

Texture2D GetTexture(const char *name) {
	if (texture_cache.data == NULL) {
		array_init(texture_cache);
	}

	for (int i = 0; i < texture_cache.length; i++) {
		if (strcmp(texture_cache.data[i].name, name) == 0) return texture_cache.data[i].tex;
	}

	char lname[256];
	strncpy(lname, name, sizeof(lname));
	lname[sizeof(lname)-1] = '\0';
	for (int i = 0; lname[i]; i++) lname[i] = tolower(lname[i]);

	char path[256];
	void *data = NULL;
	size_t size = 0;
	const char *ext = ".png";

	snprintf(path, sizeof(path), "textures/%s.png", lname);
	data = vfs_read(path, &size);
	if (!data) {
		snprintf(path, sizeof(path), "textures/%s.jpg", lname);
		data = vfs_read(path, &size);
		ext = ".jpg";
	}

	Texture2D tex = { 0 };
	if (data) {
		Image img = LoadImageFromMemory(ext, data, (int)size);
		if (img.data) {
			tex = LoadTextureFromImage(img);
			UnloadImage(img);
		}
		vfs_free(data);
	}

	if (tex.id == 0) {
		TraceLog(LOG_WARNING, "Failed to load texture: '%s'", name);
		Image img = GenImageChecked(64, 64, 8, 8, (Color){128, 128, 128, 255}, (Color){200, 200, 200, 255});
		tex = LoadTextureFromImage(img);
		UnloadImage(img);
	} else {
		GenTextureMipmaps(&tex);
		SetTextureFilter(tex, TEXTURE_FILTER_BILINEAR);
		SetTextureWrap(tex, TEXTURE_WRAP_REPEAT);
	}

	CachedTexture cached;
	strncpy(cached.name, name, sizeof(cached.name));
	cached.tex = tex;
	array_push(texture_cache, cached);

	return tex;
}

void UnloadAssets(void) {
	for (int i = 0; i < texture_cache.length; i++) {
		UnloadTexture(texture_cache.data[i].tex);
	}
	array_clear(texture_cache);
}

Font LoadFontVFS(const char *path, int fontSize) {
	size_t size = 0;
	void *data = vfs_read(path, &size);
	if (data) {
		Font font = LoadFontFromMemory(".ttf", data, (int)size, fontSize, NULL, 0);
		vfs_free(data);
		return font;
	}
	return GetFontDefault();
}