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
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
//! Functions and types relating to text rendering.

// Without this, we'd have conditionally compile a ton more stuff to
// avoid warnings when fonts are disabled:
#![cfg_attr(not(feature = "font_ttf"), allow(unused))]

mod cache;
mod packer;
#[cfg(feature = "font_ttf")]
mod vector;

use std::cell::RefCell;
use std::fmt::{self, Debug, Formatter};
use std::path::Path;
use std::rc::Rc;

use crate::error::Result;
use crate::graphics::text::cache::{FontCache, TextGeometry};
use crate::graphics::{self, DrawParams, Rectangle};
use crate::Context;

#[cfg(feature = "font_ttf")]
pub use crate::graphics::text::vector::VectorFontBuilder;

use super::FilterMode;

/// A font with an associated size, cached on the GPU.
///
/// # Performance
///
/// Creating a `Font` is a relatively expensive operation. If you can, store them in your `State`
/// struct rather than recreating them each frame.
///
/// Cloning a `Font` is a very cheap operation, as the underlying data is shared between the
/// original instance and the clone via [reference-counting](https://doc.rust-lang.org/std/rc/struct.Rc.html).
/// This does mean, however, that updating a `Font` (for example, changing its filter mode) will also
/// update any other clones of that `Font`.
///
/// # Examples
///
/// The [`text`](https://github.com/17cupsofcoffee/tetra/blob/main/examples/text.rs)
/// example demonstrates how to load a font and then draw some text.
#[derive(Clone)]
pub struct Font {
    data: Rc<RefCell<FontCache>>,
}

impl Font {
    /// Creates a `Font` from a vector font file, with the given size.
    ///
    /// TrueType and OpenType fonts are supported.
    ///
    /// If you want to load multiple sizes of the same font, you can use a
    /// [`VectorFontBuilder`] to avoid loading/parsing the file multiple times.
    ///
    /// # Errors
    ///
    /// * [`TetraError::FailedToLoadAsset`](crate::TetraError::FailedToLoadAsset) will be returned
    /// if the file could not be loaded.
    /// * [`TetraError::InvalidFont`](crate::TetraError::InvalidFont) will be returned if the font
    /// data was invalid.
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the GPU cache for the font
    ///   could not be created.
    #[cfg(feature = "font_ttf")]
    pub fn vector<P>(ctx: &mut Context, path: P, size: f32) -> Result<Font>
    where
        P: AsRef<Path>,
    {
        VectorFontBuilder::new(path)?.with_size(ctx, size)
    }

    /// Creates a `Font` from a slice of binary data.
    ///
    /// TrueType and OpenType fonts are supported.
    ///
    /// This is useful in combination with [`include_bytes`](std::include_bytes), as it
    /// allows you to include your font data directly in the binary.
    ///
    /// If you want to load multiple sizes of the same font, you can use a
    /// [`VectorFontBuilder`] to avoid parsing the data multiple times.
    ///
    /// # Errors
    ///
    /// * [`TetraError::InvalidFont`](crate::TetraError::InvalidFont) will be returned if the font
    /// data was invalid.
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the GPU cache for the font
    /// could not be created.
    #[cfg(feature = "font_ttf")]
    pub fn from_vector_file_data(
        ctx: &mut Context,
        data: &'static [u8],
        size: f32,
    ) -> Result<Font> {
        VectorFontBuilder::from_file_data(data)?.with_size(ctx, size)
    }

    /// Returns the filter mode of the font.
    pub fn filter_mode(&self) -> FilterMode {
        self.data.borrow().filter_mode()
    }

    /// Sets the filter mode of the font.
    ///
    /// Note that changing the filter mode of a font will affect all [`Text`] objects
    /// that use that font, including existing ones. This is due to the fact that
    /// each font has a shared texture atlas.
    pub fn set_filter_mode(&mut self, ctx: &mut Context, filter_mode: FilterMode) {
        self.data.borrow_mut().set_filter_mode(ctx, filter_mode);
    }
}

impl Debug for Font {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("Font").finish()
    }
}

/// A piece of text that can be rendered.
///
/// # Performance
///
/// The layout of the text is cached after the first time it is calculated, making subsequent
/// rendering of the text much faster.
///
/// Cloning a `Text` is a fairly expensive operation, as it creates an entirely new copy of the
/// object with its own cache.
///
/// # Examples
///
/// The [`text`](https://github.com/17cupsofcoffee/tetra/blob/main/examples/text.rs)
/// example demonstrates how to load a font and then draw some text.
#[derive(Debug, Clone)]
pub struct Text {
    content: String,
    font: Font,
    max_width: Option<f32>,
    geometry: Option<TextGeometry>,
}

impl Text {
    /// Creates a new `Text`, with the given content and font.
    pub fn new<C>(content: C, font: Font) -> Text
    where
        C: Into<String>,
    {
        Text {
            content: content.into(),
            font,
            max_width: None,
            geometry: None,
        }
    }

    /// Creates a new wrapped `Text`, with the given content, font
    /// and maximum width.
    ///
    /// If a word is too long to fit, it may extend beyond the max width - use
    /// [`get_bounds`](Text::get_bounds) if you need to find the actual bounds
    /// of the text.
    pub fn wrapped<C>(content: C, font: Font, max_width: f32) -> Text
    where
        C: Into<String>,
    {
        Text {
            content: content.into(),
            font,
            max_width: Some(max_width),
            geometry: None,
        }
    }

    /// Draws the text to the screen (or to a canvas, if one is enabled).
    pub fn draw<P>(&mut self, ctx: &mut Context, params: P)
    where
        P: Into<DrawParams>,
    {
        self.update_geometry(ctx);

        let params = params.into();

        let data = self.font.data.borrow();
        graphics::set_texture(ctx, data.texture());

        let geometry = self
            .geometry
            .as_ref()
            .expect("geometry should have been generated");

        for quad in &geometry.quads {
            graphics::push_quad(
                ctx,
                quad.position.x,
                quad.position.y,
                quad.position.right(),
                quad.position.bottom(),
                quad.uv.x,
                quad.uv.y,
                quad.uv.right(),
                quad.uv.bottom(),
                &params,
            );
        }
    }

    /// Returns a reference to the content of the text.
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Sets the content of the text.
    ///
    /// Calling this function will cause a re-layout of the text the next time it
    /// is rendered.
    pub fn set_content<C>(&mut self, content: C)
    where
        C: Into<String>,
    {
        self.geometry.take();
        self.content = content.into();
    }

    /// Gets the font of the text.
    pub fn font(&self) -> &Font {
        &self.font
    }

    /// Sets the font of the text.
    ///
    /// Calling this function will cause a re-layout of the text the next time it
    /// is rendered.
    pub fn set_font(&mut self, font: Font) {
        self.geometry.take();
        self.font = font;
    }

    /// Gets the maximum width of the text, if one is set.
    ///
    /// If a word is too long to fit, it may extend beyond this width - use
    /// [`get_bounds`](Text::get_bounds) if you need to find the actual bounds
    /// of the text.
    pub fn max_width(&self) -> Option<f32> {
        self.max_width
    }

    /// Sets the maximum width of the text.
    ///
    /// If `Some` is passed, word-wrapping will be enabled. If `None` is passed,
    /// it will be disabled.
    ///
    /// If a word is too long to fit, it may extend beyond this width - use
    /// [`get_bounds`](Text::get_bounds) if you need to find the actual bounds
    /// of the text.
    ///
    /// Calling this function will cause a re-layout of the text the next time it
    /// is rendered.
    pub fn set_max_width(&mut self, max_width: Option<f32>) {
        self.geometry.take();
        self.max_width = max_width;
    }

    /// Appends the given character to the end of the text.
    ///
    /// Calling this function will cause a re-layout of the text the next time it
    /// is rendered.
    pub fn push(&mut self, ch: char) {
        self.geometry.take();
        self.content.push(ch);
    }

    /// Appends the given string slice to the end of the text.
    ///
    /// Calling this function will cause a re-layout of the text the next time it
    /// is rendered.
    pub fn push_str(&mut self, string: &str) {
        self.geometry.take();
        self.content.push_str(string);
    }

    /// Removes the last character from the text and returns it.
    ///
    /// Returns [`None`] if the text is empty.
    ///
    /// Calling this function will cause a re-layout of the text the next time it
    /// is rendered.
    pub fn pop(&mut self) -> Option<char> {
        self.geometry.take();
        self.content.pop()
    }

    /// Get the outer bounds of the text when rendered to the screen.
    ///
    /// If the text's layout needs calculating, this method will do so.
    ///
    /// Note that this method will not take into account the positioning applied to the text via [`DrawParams`].
    pub fn get_bounds(&mut self, ctx: &mut Context) -> Option<Rectangle> {
        self.update_geometry(ctx);

        self.geometry
            .as_ref()
            .expect("geometry should have been generated")
            .bounds
    }

    fn update_geometry(&mut self, ctx: &mut Context) {
        let mut data = self.font.data.borrow_mut();

        let needs_render = match &self.geometry {
            None => true,
            Some(g) => g.resize_count != data.resize_count(),
        };

        if needs_render {
            let new_geometry = data.render(&mut ctx.device, &self.content, self.max_width);
            self.geometry = Some(new_geometry);
        }
    }
}