1#include "all.h"
2
3#include <stdio.h>
4#include <string.h>
5#include <ctype.h>
6
7static array(CachedTexture) texture_cache;
8
9Texture2D get_texture(const char *name) {
10 if (texture_cache.data == NULL) {
11 array_init(texture_cache);
12 }
13
14 for (int i = 0; i < texture_cache.length; i++) {
15 if (strcmp(texture_cache.data[i].name, name) == 0) return texture_cache.data[i].tex;
16 }
17
18 char lname[256];
19 strncpy(lname, name, sizeof(lname));
20 lname[sizeof(lname)-1] = '\0';
21 for (int i = 0; lname[i]; i++) lname[i] = tolower(lname[i]);
22
23 char path[256];
24 void *data = NULL;
25 size_t size = 0;
26 const char *ext = ".png";
27
28 snprintf(path, sizeof(path), "textures/%s.png", lname);
29 data = vfs_read(path, &size);
30 if (!data) {
31 snprintf(path, sizeof(path), "textures/%s.jpg", lname);
32 data = vfs_read(path, &size);
33 ext = ".jpg";
34 }
35
36 Texture2D tex = { 0 };
37 if (data) {
38 Image img = LoadImageFromMemory(ext, data, (int)size);
39 if (img.data) {
40 tex = LoadTextureFromImage(img);
41 UnloadImage(img);
42 }
43 vfs_free(data);
44 }
45
46 if (tex.id == 0) {
47 TraceLog(LOG_WARNING, "Failed to load texture: '%s'", name);
48 Image img = GenImageChecked(64, 64, 8, 8, (Color){128, 128, 128, 255}, (Color){200, 200, 200, 255});
49 tex = LoadTextureFromImage(img);
50 UnloadImage(img);
51 } else {
52 SetTextureFilter(tex, TEXTURE_FILTER_POINT);
53 SetTextureWrap(tex, TEXTURE_WRAP_REPEAT);
54 }
55
56 CachedTexture cached;
57 strncpy(cached.name, name, sizeof(cached.name));
58 cached.tex = tex;
59 array_push(texture_cache, cached);
60
61 return tex;
62}
63
64void unload_assets(void) {
65 for (int i = 0; i < texture_cache.length; i++) {
66 UnloadTexture(texture_cache.data[i].tex);
67 }
68 array_clear(texture_cache);
69}
70
71Font load_font_vfs(const char *path, int fontSize) {
72 size_t size = 0;
73 void *data = vfs_read(path, &size);
74 if (data) {
75 Font font = LoadFontFromMemory(".ttf", data, (int)size, fontSize, NULL, 0);
76 vfs_free(data);
77 return font;
78 }
79 return GetFontDefault();
80}