diff --git a/CMakeLists.txt b/CMakeLists.txt index 578ed1b..b6b0b06 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,6 +27,6 @@ set(SRC # add the executable add_executable(FLOPPE_FION ${SRC}) -target_link_libraries(FLOPPE_FION SDL2 SDL_image pthread m) +target_link_libraries(FLOPPE_FION SDL2 SDL_image SDL_ttf pthread m) set_property(TARGET FLOPPE_FION PROPERTY C_STANDARD 23) diff --git a/src/text.c b/src/text.c new file mode 100644 index 0000000..b889b6e --- /dev/null +++ b/src/text.c @@ -0,0 +1,65 @@ +#include "text.h" +#include + +#define FONT_CACHE_SIZE 100 +#define MAX_TEXT_SIZE 100 + +typedef struct FontCacheObject { + char* file; + int size; + TTF_Font* font; +} FontCacheObject_t; + +FontCacheObject_t fontCache[FONT_CACHE_SIZE]; +unsigned fontCacheSize = 0; + +void text_freeFontCache(void){ + for(unsigned i = 0; i < fontCacheSize; ++i){ + free(fontCache[i].file); + TTF_CloseFont(fontCache[i].font); + } +} + +int text_renderText(RenderObject_t* renderObject, Position position, SDL_Color color, const char* fontFilename, int fontSize, char* format, ...){ + + TTF_Font* font = NULL; + for(unsigned i = 0; i < fontCacheSize; ++i){ + if(strcmp(fontCache[i].file, fontFilename) && fontCache[i].size == fontSize){ + font = fontCache[i].font; + break; + } + } + if(font == NULL) { + font = TTF_OpenFont(fontFilename, fontSize); + if(font == NULL) { + SDL_LogError(SDL_LOG_PRIORITY_ERROR, "TTF_OpenFont"); + return -1; + } + FontCacheObject_t fontCacheObject; + fontCacheObject.file = (char*)malloc(strlen(fontFilename) + 1); + strcpy(fontCacheObject.file, fontFilename); + fontCacheObject.size = fontSize; + fontCacheObject.font = font; + fontCache[fontCacheSize] = fontCacheObject; + ++fontCacheSize; + } + + char text[MAX_TEXT_SIZE]; + va_list args; + + memset(&text, '\0', sizeof(text)); + + va_start(args, format); + vsprintf(text, format, args); + va_end(args); + + SDL_Surface* surface = TTF_RenderText_Blended(font, text, color); + + + renderObject->x = position.x; + renderObject->y = position.y; + renderObject->z = position.z; + renderObject->surface = surface; + + return 0; +} diff --git a/src/text.h b/src/text.h new file mode 100644 index 0000000..354a40f --- /dev/null +++ b/src/text.h @@ -0,0 +1,18 @@ +#ifndef __TEXT_H__ +#define __TEXT_H__ + +#include +#include "renderer.h" + +typedef struct { + int x; + int y; + int z; +} Position; + + +int text_renderText(RenderObject_t* renderObject, Position position, SDL_Color color, const char* fontFilename, int fontSize, char* format, ...); + +void text_freeFontCache(void); + +#endif