Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_text/src/font.rs
9370 views
1
use crate::ComputedTextBlock;
2
use crate::FontCx;
3
use bevy_asset::Asset;
4
use bevy_asset::AssetEvent;
5
use bevy_asset::Assets;
6
use bevy_ecs::message::MessageReader;
7
use bevy_ecs::system::Query;
8
use bevy_ecs::system::Res;
9
use bevy_ecs::system::ResMut;
10
use bevy_reflect::TypePath;
11
use parley::fontique::Blob;
12
use parley::fontique::FontInfoOverride;
13
use smol_str::SmolStr;
14
15
/// An [`Asset`] that contains the data for a loaded font, if loaded as an asset.
16
///
17
/// Loaded by [`FontLoader`](crate::FontLoader).
18
///
19
/// # A note on fonts
20
///
21
/// `Font` may differ from the everyday notion of what a "font" is.
22
/// A font *face* (e.g. Fira Sans Semibold Italic) is part of a font *family* (e.g. Fira Sans),
23
/// and is distinguished from other font faces in the same family
24
/// by its style (e.g. italic), its weight (e.g. bold) and its stretch (e.g. condensed).
25
///
26
/// Bevy currently loads a single font face as a single `Font` asset.
27
#[derive(Debug, TypePath, Clone, Asset)]
28
pub struct Font {
29
/// Content of a font file as bytes
30
pub data: Blob<u8>,
31
/// Font family name.
32
/// If the font file is a collection with multiple families, the first family name from the last font is used.
33
pub family_name: SmolStr,
34
}
35
36
impl Font {
37
/// Creates a [`Font`] from bytes
38
pub fn try_from_bytes(font_data: Vec<u8>, family_name: &str) -> Font {
39
Self {
40
data: Blob::from(font_data),
41
family_name: family_name.into(),
42
}
43
}
44
}
45
46
/// Add new font assets to the internal font collection.
47
pub fn load_font_assets_into_font_collection(
48
fonts: Res<Assets<Font>>,
49
mut events: MessageReader<AssetEvent<Font>>,
50
mut font_cx: ResMut<FontCx>,
51
mut text_block_query: Query<&mut ComputedTextBlock>,
52
) {
53
let mut new_fonts_added = false;
54
55
for event in events.read() {
56
if let AssetEvent::Added { id } = event
57
&& let Some(font) = fonts.get(*id)
58
{
59
font_cx.0.collection.register_fonts(
60
font.data.clone(),
61
Some(FontInfoOverride {
62
family_name: Some(font.family_name.as_str()),
63
..Default::default()
64
}),
65
);
66
new_fonts_added = true;
67
}
68
}
69
70
// Whenever new fonts are added, update all text blocks so they use the new fonts.
71
if new_fonts_added {
72
for mut block in text_block_query.iter_mut() {
73
block.needs_rerender = true;
74
}
75
}
76
}
77
78