rafx_plugins/features/text/
text_resource.rs

1use super::{TextDrawCommand, TextDrawData};
2use crate::assets::font::FontAsset;
3use fnv::FnvHashMap;
4use hydrate_base::handle::{ArtifactHandle, Handle};
5use hydrate_base::LoadHandle;
6
7pub struct AppendText<'a>(&'a mut TextResource, glam::Vec3);
8
9impl<'a> AppendText<'a> {
10    pub fn append(
11        self,
12        text: String,
13        font: &Handle<FontAsset>,
14        size: f32,
15        color: glam::Vec4,
16    ) -> AppendText<'a> {
17        self.0.do_add_text(text, self.1, font, size, color, true)
18    }
19}
20
21pub struct TextResource {
22    fonts: FnvHashMap<LoadHandle, Handle<FontAsset>>,
23    text_draw_commands: Vec<TextDrawCommand>,
24}
25
26impl TextResource {
27    pub fn new() -> Self {
28        TextResource {
29            fonts: Default::default(),
30            text_draw_commands: Default::default(),
31        }
32    }
33
34    pub fn add_text(
35        &mut self,
36        text: String,
37        position: glam::Vec3,
38        font: &Handle<FontAsset>,
39        size: f32,
40        color: glam::Vec4,
41    ) -> AppendText {
42        self.do_add_text(text, position, font, size, color, false)
43    }
44
45    pub(super) fn do_add_text(
46        &mut self,
47        text: String,
48        position: glam::Vec3,
49        font: &Handle<FontAsset>,
50        size: f32,
51        color: glam::Vec4,
52        is_append: bool,
53    ) -> AppendText {
54        let font = self.fonts.entry(font.load_handle()).or_insert(font.clone());
55
56        self.text_draw_commands.push(TextDrawCommand {
57            text,
58            position,
59            font: font.load_handle(),
60            size,
61            color,
62            is_append,
63        });
64
65        AppendText(self, position)
66    }
67
68    // Returns the draw data, leaving this object in an empty state
69    pub(super) fn take_text_draw_data(&mut self) -> TextDrawData {
70        TextDrawData {
71            fonts: std::mem::take(&mut self.fonts),
72            text_draw_commands: std::mem::take(&mut self.text_draw_commands),
73        }
74    }
75
76    // Recommended to call every frame to ensure that this doesn't grow unbounded
77    pub fn clear(&mut self) {
78        self.take_text_draw_data();
79    }
80}