hibiscus/renderer/rsdl/rsdl.cpp

100 lines
2.6 KiB
C++

#include <SDL2/SDL_ttf.h>
#include <fmt/format.h>
#include "rsdl.hpp"
#include "resources/font.hpp"
#include <pragmautil.hpp>
namespace hibis::rsdl {
RSDL::RSDL(std::string title, IntVec2 size, LoggerCallback callback) {
mLoggerCallback = callback;
SDL_Init(SDL_INIT_VIDEO);
// Create window. `title` is cast to a char* here as tostd::stringz returns an immutable char* (causing an error)
mWindow = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
size.x, size.y, SDL_WINDOW_RESIZABLE);
if (mWindow == NULL) {
mLoggerCallback(Fatal, fmt::format("Couldn't create window! what: {}", SDL_GetError()));
SDL_Quit();
exit(1);
}
mRendererContext = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_ACCELERATED);
if (mRendererContext == NULL) {
mLoggerCallback(Fatal, fmt::format("Couldn't create renderer! what: {}", SDL_GetError()));
SDL_DestroyWindow(mWindow);
SDL_Quit();
exit(1);
}
if (TTF_Init() != 0) {
mLoggerCallback(Fatal, fmt::format("Couldn't load SDL_TTF! what: %d", TTF_GetError()));
SDL_DestroyRenderer(mRendererContext);
SDL_DestroyWindow(mWindow);
SDL_Quit();
TTF_Quit();
exit(1);
}
}
RSDL::~RSDL() {
TTF_Quit();
SDL_DestroyRenderer(mRendererContext);
SDL_DestroyWindow(mWindow);
SDL_Quit();
}
void RSDL::clearScreen(Color col) {
SDL_SetRenderDrawColor(mRendererContext, col.r, col.g, col.b, col.a);
SDL_RenderClear(mRendererContext);
}
void RSDL::renderCurrent() {
SDL_UpdateWindowSurface(mWindow);
SDL_RenderPresent(mRendererContext);
}
void RSDL::drawText(Resource* resource, std::string text, IntVec2 pos, Color color) {
WARNING("tulip what the hell is this, this sucks.\nAvoid remaking textures every time text has to be drawn")
if (Font* font = (Font*)resource) {
SDL_Surface* textSurface = TTF_RenderText_Solid(font->mLoadedFont, text.c_str(), SDL_Color {color.r, color.g, color.b, color.a });
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(mRendererContext, textSurface);
int width = 0;
int height = 0;
TTF_SizeText(font->mLoadedFont, text.c_str(), &width, &height);
SDL_Rect textRect;
textRect.x = pos.x;
textRect.y = pos.y;
textRect.w = width;
textRect.h = height;
SDL_RenderCopy(mRendererContext, textTexture, NULL, &textRect);
SDL_DestroyTexture(textTexture);
SDL_FreeSurface(textSurface);
}
}
void RSDL::preDraw() {}
void RSDL::postDraw() {}
void RSDL::update() {
SDL_Event event;
while(SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) mKeepOpen = false;
}
}
void RSDL::setWindowTitle(std::string title) {
SDL_SetWindowTitle(mWindow, title.c_str());
}
}