1 #include <shadowdive/shadowdive.h>
2
3 #include "utils/log.h"
4 #include "utils/vector.h"
5 #include "video/surface.h"
6 #include "resources/ids.h"
7 #include "resources/fonts.h"
8 #include "resources/pathmanager.h"
9
10 font font_small;
11 font font_large;
12 static int fonts_loaded = 0;
13
font_create(font * f)14 void font_create(font *f) {
15 memset(f, 0, sizeof(font));
16 vector_create(&f->surfaces, sizeof(surface*));
17 }
18
font_free(font * font)19 void font_free(font *font) {
20 iterator it;
21 vector_iter_begin(&font->surfaces, &it);
22 surface **sur = NULL;
23 while((sur = iter_next(&it)) != NULL) {
24 surface_free(*sur);
25 free(*sur);
26 }
27 vector_free(&font->surfaces);
28 }
29
font_load(font * font,const char * filename,unsigned int size)30 int font_load(font *font, const char* filename, unsigned int size) {
31 sd_rgba_image img;
32 sd_font sdfont;
33 int pixsize;
34 surface *sur;
35
36 // Find vertical size
37 switch(size) {
38 case FONT_BIG: pixsize = 8; break;
39 case FONT_SMALL: pixsize = 6; break;
40 default:
41 return 1;
42 }
43
44 // Open font file
45 if(sd_font_create(&sdfont) != SD_SUCCESS) {
46 return 1;
47 }
48 if(sd_font_load(&sdfont, filename, pixsize)) {
49 sd_font_free(&sdfont);
50 return 2;
51 }
52
53 // Load into textures
54 sd_rgba_image_create(&img, pixsize, pixsize);
55 for(int i = 0; i < 224; i++) {
56 sur = malloc(sizeof(surface));
57 sd_font_decode(&sdfont, &img, i, 0xFF, 0xFF, 0xFF);
58 surface_create_from_data(sur, SURFACE_TYPE_RGBA, img.w, img.h, img.data);
59 vector_append(&font->surfaces, &sur);
60 }
61
62 // Set font info vars
63 font->w = pixsize;
64 font->h = pixsize;
65 font->size = size;
66
67 // Free resources
68 sd_rgba_image_free(&img);
69 sd_font_free(&sdfont);
70 return 0;
71 }
72
fonts_init()73 int fonts_init() {
74 font_create(&font_small);
75 font_create(&font_large);
76 const char *filename = NULL;
77
78 // Load small font
79 filename = pm_get_resource_path(DAT_CHARSMAL);
80 if(font_load(&font_small, filename, FONT_SMALL)) {
81 PERROR("Unable to load font file '%s'!", filename);
82 goto error_2;
83 }
84 INFO("Loaded font file '%s'", filename);
85
86 // Load big font
87 filename = pm_get_resource_path(DAT_GRAPHCHR);
88 if(font_load(&font_large, filename, FONT_BIG)) {
89 PERROR("Unable to load font file '%s'!", filename);
90 goto error_1;
91 }
92 INFO("Loaded font file '%s'", filename);
93
94 // All done.
95 fonts_loaded = 1;
96 return 0;
97
98 error_2:
99 font_free(&font_small);
100 error_1:
101 font_free(&font_large);
102 return 1;
103 }
104
fonts_close()105 void fonts_close() {
106 if(fonts_loaded) {
107 font_free(&font_small);
108 font_free(&font_large);
109 fonts_loaded = 0;
110 }
111 }