Skip to content

Add support for OpenType features in text (e.g. ligatures, smallcaps) #19020

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions assets/fonts/EBGaramond-LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
Copyright (c) 2010-2013 Georg Duffner (http://www.georgduffner.at)

All "EB Garamond" Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL


-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file added assets/fonts/EBGaramond12-Regular.otf
Binary file not shown.
1 change: 1 addition & 0 deletions crates/bevy_text/src/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,7 @@ fn get_attrs<'a>(
}
.scale(scale_factor as f32),
)
.font_features((&text_font.font_features).into())
.color(cosmic_text::Color(color.to_linear().as_u32()));
attrs
}
Expand Down
166 changes: 166 additions & 0 deletions crates/bevy_text/src/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,8 @@ pub struct TextFont {
pub line_height: LineHeight,
/// The antialiasing method to use when rendering text.
pub font_smoothing: FontSmoothing,
/// OpenType features for .otf fonts that support them.
pub font_features: FontFeatures,
}

impl TextFont {
Expand Down Expand Up @@ -351,11 +353,175 @@ impl Default for TextFont {
font: Default::default(),
font_size: 20.0,
line_height: LineHeight::default(),
font_features: FontFeatures::default(),
font_smoothing: Default::default(),
}
}
}

/// OpenType features for .otf fonts that support them.
///
/// Examples features include ligatures, small-caps, and fractional number display. For the complete
/// list of OpenType features, see the spec at
/// `<https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist>`.
///
/// # Usage:
/// ```
/// use bevy_text::FontFeatures;
///
/// // Create using the builder
/// let font_features = FontFeatures::builder()
/// .enable(FontFeatures::STANDARD_LIGATURES)
/// .set(FontFeatures::WEIGHT, 300)
/// .build();
///
/// // Create from a list
/// let more_font_features: FontFeatures = [
/// FontFeatures::STANDARD_LIGATURES,
/// FontFeatures::OLDSTYLE_FIGURES,
/// FontFeatures::TABULAR_FIGURES
/// ].into();
/// ```
#[derive(Clone, Debug, Default, Reflect)]
pub struct FontFeatures {
features: Vec<([u8; 4], u32)>,
}

impl FontFeatures {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree that an enum with 100+ variants might be burdensome to maintain, but maybe some constants for commonly used features might be useful like:

Suggested change
impl FontFeatures {
impl FontFeatures {
pub const SUPERSCRIPT: [u8; 4] = b"sups";

and so on

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, will do! I think that will be helpful. I'll update the PR on Monday.

/// Replaces character combinations like fi, fl with ligatures.
pub const STANDARD_LIGATURES: [u8; 4] = *b"liga";

/// Enables ligatures based on character context.
pub const CONTEXTUAL_LIGATURES: [u8; 4] = *b"clig";

/// Enables optional ligatures for stylistic use (e.g., ct, st).
pub const DISCRETIONARY_LIGATURES: [u8; 4] = *b"dlig";

/// Adjust glyph shapes based on surrounding letters.
pub const CONTEXTUAL_ALTERNATES: [u8; 4] = *b"calt";

/// Use alternate glyph designs.
pub const STYLISTIC_ALTERNATES: [u8; 4] = *b"salt";

/// Replaces lowercase letters with small caps.
pub const SMALL_CAPS: [u8; 4] = *b"smcp";

/// Replaces uppercase letters with small caps.
pub const CAPS_TO_SMALL_CAPS: [u8; 4] = *b"c2sc";

/// Replaces characters with swash versions (often decorative).
pub const SWASH: [u8; 4] = *b"swsh";

/// Enables alternate glyphs for large sizes or titles.
pub const TITLING_ALTERNATES: [u8; 4] = *b"titl";

/// Converts numbers like 1/2 into true fractions (½).
pub const FRACTIONS: [u8; 4] = *b"frac";

/// Formats characters like 1st, 2nd properly.
pub const ORDINALS: [u8; 4] = *b"ordn";

/// Uses a slashed version of zero (0) to differentiate from O.
pub const SLASHED_ZERO: [u8; 4] = *b"ordn";

/// Replaces figures with superscript figures, e.g. for indicating footnotes.
pub const SUPERSCRIPT: [u8; 4] = *b"sups";

/// Replaces figures with subscript figures.
pub const SUBSCRIPT: [u8; 4] = *b"subs";

/// Changes numbers to "oldstyle" form, which fit better in the flow of sentences or other text.
pub const OLDSTYLE_FIGURES: [u8; 4] = *b"onum";

/// Changes numbers to "lining" form, which are better suited for standalone numbers. When
/// enabled, the bottom of all numbers will be aligned with each other.
pub const LINING_FIGURES: [u8; 4] = *b"lnum";

/// Changes numbers to be of proportional width. When enabled, numbers may have varying widths.
pub const PROPORTIONAL_FIGURES: [u8; 4] = *b"pnum";

/// Changes numbers to be of uniform (tabular) width. When enabled, all numbers will have the
/// same width.
pub const TABULAR_FIGURES: [u8; 4] = *b"tnum";

/// Varies the stroke thickness. Values must be in the range of 0 to 1000.
pub const WEIGHT: [u8; 4] = *b"wght";

/// Varies the width of text from narrower to wider. Must be a value greater than 0. A value of
/// 100 is typically considered standard width.
pub const WIDTH: [u8; 4] = *b"wdth";

/// Varies between upright and slanted text. Must be a value greater than -90 and less than +90.
/// A value of 0 is upright.
pub const SLANT: [u8; 4] = *b"slnt";

/// Create a new [`FontFeaturesBuilder`].
pub fn builder() -> FontFeaturesBuilder {
FontFeaturesBuilder::default()
}
}

/// A builder for [`FontFeatures`].
#[derive(Clone, Default)]
pub struct FontFeaturesBuilder {
features: Vec<([u8; 4], u32)>,
}

impl FontFeaturesBuilder {
/// Enable an OpenType feature.
///
/// Most OpenType features are on/off switches, so this is a convenience method that sets the
/// feature's value to "1" (enabled). For non-boolean features, see [`FontFeaturesBuilder::set`].
pub fn enable(self, feature: [u8; 4]) -> Self {
self.set(feature, 1)
}

/// Set an OpenType feature to a specific value.
///
/// For most features, the [`FontFeaturesBuilder::enable`] method should be used instead. A few
/// features, such as "wght", take numeric values, so this method may be used for these cases.
pub fn set(mut self, feature: [u8; 4], value: u32) -> Self {
self.features.push((feature, value));
self
}

/// Build a [`FontFeatures`] from the values set within this builder.
pub fn build(self) -> FontFeatures {
FontFeatures {
features: self.features,
}
}
}

/// Allow [`FontFeatures`] to be built from a list. This is suitable for the standard case when each
/// listed feature is a boolean type. If any features require a numeric value (like "wght"), use
/// [`FontFeaturesBuilder`] instead.
impl<T> From<T> for FontFeatures
where
T: IntoIterator<Item = [u8; 4]>,
{
fn from(value: T) -> Self {
FontFeatures {
features: value.into_iter().map(|x| (x, 1)).collect(),
}
}
}

impl From<&FontFeatures> for cosmic_text::FontFeatures {
fn from(font_features: &FontFeatures) -> Self {
cosmic_text::FontFeatures {
features: font_features
.features
.iter()
.map(|(tag, value)| cosmic_text::Feature {
tag: cosmic_text::FeatureTag::new(tag),
value: *value,
})
.collect(),
}
}
}

/// Specifies the height of each line of text for `Text` and `Text2d`
///
/// Default is 1.2x the font size
Expand Down
63 changes: 63 additions & 0 deletions examples/ui/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use bevy::{
color::palettes::css::GOLD,
diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin},
prelude::*,
text::FontFeatures,
};

fn main() {
Expand Down Expand Up @@ -88,6 +89,68 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
FpsText,
));

// Text with OpenType features
let opentype_font_handle = asset_server.load("fonts/EBGaramond12-Regular.otf");
commands
.spawn((
Node {
margin: UiRect::all(Val::Px(12.0)),
position_type: PositionType::Absolute,
top: Val::Px(5.0),
right: Val::Px(5.0),
..default()
},
Text::new("Opentype features:\n"),
TextFont {
font: opentype_font_handle.clone(),
font_size: 32.0,
..default()
},
))
.with_children(|parent| {
let text_rows = [
("Smallcaps: ", FontFeatures::SMALL_CAPS, "Hello World"),
(
"Ligatures: ",
FontFeatures::STANDARD_LIGATURES,
"fi fl ff ffi ffl",
),
("Fractions: ", FontFeatures::FRACTIONS, "12/134"),
("Superscript: ", FontFeatures::SUPERSCRIPT, "Up here!"),
("Subscript: ", FontFeatures::SUBSCRIPT, "Down here!"),
(
"Oldstyle figures: ",
FontFeatures::OLDSTYLE_FIGURES,
"1234567890",
),
(
"Lining figures: ",
FontFeatures::LINING_FIGURES,
"1234567890",
),
];

for (title, feature, text) in text_rows {
parent.spawn((
TextSpan::new(title),
TextFont {
font: opentype_font_handle.clone(),
font_size: 24.0,
..default()
},
));
parent.spawn((
TextSpan::new(format!("{text}\n")),
TextFont {
font: opentype_font_handle.clone(),
font_size: 24.0,
font_features: FontFeatures::builder().enable(feature).build(),
..default()
},
));
}
});

#[cfg(feature = "default_font")]
commands.spawn((
// Here we are able to call the `From` method instead of creating a new `TextSection`.
Expand Down
Loading