Files
dusk/src/dusk/display/text/text.c
2026-03-08 12:01:22 -05:00

128 lines
2.6 KiB
C

/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "text.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "display/spritebatch/spritebatch.h"
#include "asset/asset.h"
texture_t DEFAULT_FONT_TEXTURE;
tileset_t DEFAULT_FONT_TILESET;
errorret_t textInit(void) {
// errorChain(assetLoad("ui/minogram.dpt", &DEFAULT_FONT_TEXTURE));
// errorChain(assetLoad("ui/minogram.dtf", &DEFAULT_FONT_TILESET));
errorOk();
}
errorret_t textDispose(void) {
// errorChain(textureDispose(&DEFAULT_FONT_TEXTURE));
errorOk();
}
errorret_t textDrawChar(
const float_t x,
const float_t y,
const char_t c,
const color_t color,
const tileset_t *tileset,
texture_t *texture
) {
int32_t tileIndex = (int32_t)(c) - TEXT_CHAR_START;
if(tileIndex < 0 || tileIndex >= tileset->tileCount) {
tileIndex = ((int32_t)'@') - TEXT_CHAR_START;
}
assertTrue(
tileIndex >= 0 && tileIndex <= tileset->tileCount,
"Character is out of bounds for font tiles"
);
vec4 uv;
tilesetTileGetUV(tileset, tileIndex, uv);
errorChain(spriteBatchPush(
texture,
x, y,
x + tileset->tileWidth,
y + tileset->tileHeight,
color,
uv[0], uv[1], uv[2], uv[3]
));
errorOk();
}
errorret_t textDraw(
const float_t x,
const float_t y,
const char_t *text,
const color_t color,
const tileset_t *tileset,
texture_t *texture
) {
assertNotNull(text, "Text cannot be NULL");
float_t posX = x;
float_t posY = y;
char_t c;
int32_t i = 0;
while((c = text[i++]) != '\0') {
if(c == '\n') {
posX = x;
posY += tileset->tileHeight;
continue;
}
if(c == ' ') {
posX += tileset->tileWidth;
continue;
}
errorChain(textDrawChar(posX, posY, c, color, tileset, texture));
posX += tileset->tileWidth;
}
errorOk();
}
void textMeasure(
const char_t *text,
const tileset_t *tileset,
int32_t *outWidth,
int32_t *outHeight
) {
assertNotNull(text, "Text cannot be NULL");
assertNotNull(outWidth, "Output width pointer cannot be NULL");
assertNotNull(outHeight, "Output height pointer cannot be NULL");
int32_t width = 0;
int32_t height = tileset->tileHeight;
int32_t lineWidth = 0;
char_t c;
int32_t i = 0;
while((c = text[i++]) != '\0') {
if(c == '\n') {
if(lineWidth > width) {
width = lineWidth;
}
lineWidth = 0;
height += tileset->tileHeight;
continue;
}
lineWidth += tileset->tileWidth;
}
if(lineWidth > width) {
width = lineWidth;
}
*outWidth = width;
*outHeight = height;
}