summaryrefslogtreecommitdiff
path: root/pixel-client/src/render/font.rs
blob: 96347d2517b389b2cf01d4f5cacc9009123fbffd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
    Hurry Curry! - a game about cooking
    Copyright 2024 metamuffin

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/
use super::{sprite::SpriteDraw, AtlasLayout, Renderer};
use hurrycurry_protocol::glam::Vec2;
use sdl2::rect::Rect;

pub struct FontTextures {
    pub glyphs: [Rect; 128],
}

impl FontTextures {
    pub fn init(layout: &AtlasLayout) -> Self {
        FontTextures {
            glyphs: (0..128)
                .map(|n| {
                    layout
                        .get(&format!("letter_{n}+a"))
                        .copied()
                        .unwrap_or(Rect::new(0, 0, 0, 0))
                })
                .collect::<Vec<_>>()
                .try_into()
                .expect("some letters are missing in the font"),
        }
    }
}

impl Renderer<'_> {
    pub fn draw_text(
        &mut self,
        position: Vec2,
        text: &str,
        scale: f32,
        tint: Option<[u8; 4]>,
    ) -> Vec2 {
        let mut cursor = position;
        let mut line_height = 0f32;
        for c in text.chars() {
            if c == '\n' {
                cursor.y += line_height;
                cursor.x = position.x
            }
            if (c as u32) < 128 {
                let r = self.font_textures.glyphs[c as usize];
                let size = Vec2::new(r.width() as f32, r.height() as f32) * scale;
                self.draw_ui(SpriteDraw::overlay(r, cursor, size, tint));
                cursor.x += size.x;
                line_height = line_height.max(size.y)
            }
        }
        (cursor - position.y) + Vec2::Y * line_height
    }
}