use crate::math::{Position, Color, Vec2};
use crate::EngineResult;
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FontConfig {
pub name: String,
pub size: f32,
pub path: Option<String>,
}
impl Default for FontConfig {
fn default() -> Self {
Self {
name: "default".to_string(),
size: 16.0,
path: None,
}
}
}
#[derive(Debug, Clone)]
pub struct TextComponent {
pub text: String,
pub font: String,
pub size: f32,
pub color: Color,
pub position: Position,
pub scale: Vec2,
pub visible: bool,
}
impl Default for TextComponent {
fn default() -> Self {
Self {
text: String::new(),
font: "default".to_string(),
size: 16.0,
color: Color::new(1.0, 1.0, 1.0, 1.0),
position: Position::new(0.0, 0.0),
scale: Vec2::new(1.0, 1.0),
visible: true,
}
}
}
impl TextComponent {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
..Default::default()
}
}
pub fn with_font(mut self, font: impl Into<String>) -> Self {
self.font = font.into();
self
}
pub fn with_size(mut self, size: f32) -> Self {
self.size = size;
self
}
pub fn with_color(mut self, color: Color) -> Self {
self.color = color;
self
}
pub fn with_position(mut self, position: Position) -> Self {
self.position = position;
self
}
pub fn with_scale(mut self, scale: Vec2) -> Self {
self.scale = scale;
self
}
}
pub struct TextRenderer {
fonts: HashMap<String, FontConfig>,
}
impl TextRenderer {
pub fn new() -> EngineResult<Self> {
let mut fonts = HashMap::new();
fonts.insert("default".to_string(), FontConfig::default());
Ok(Self {
fonts,
})
}
pub fn add_font(&mut self, name: impl Into<String>, config: FontConfig) {
self.fonts.insert(name.into(), config);
}
pub fn prepare_text_for_rendering(&self, text_component: &TextComponent) -> Option<TextRenderData> {
if !text_component.visible || text_component.text.is_empty() {
return None;
}
Some(TextRenderData {
text: text_component.text.clone(),
position: text_component.position,
size: text_component.size,
color: text_component.color,
font: text_component.font.clone(),
})
}
}
#[derive(Debug, Clone)]
pub struct TextRenderData {
pub text: String,
pub position: Position,
pub size: f32,
pub color: Color,
pub font: String,
}