Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
f5667c6
* Added `Weight` type, a u16 wrapper identical to `cosmic_text::Weight`.
ickshonpe Dec 5, 2025
94a07dd
Improved font weight docs
ickshonpe Dec 5, 2025
93e5f90
Cleanup
ickshonpe Dec 5, 2025
7af1fc0
Improve docs and added `clamp` function to `Weight`.
ickshonpe Dec 5, 2025
8ba4a4f
Add `Weight` to `prelude`
ickshonpe Dec 5, 2025
5bfa0ae
Added `font_weights` example.
ickshonpe Dec 5, 2025
2ebe0b3
Use the EbGaramond12-regular font in the font weights example.
ickshonpe Dec 5, 2025
0e964d5
Removed the `weight` field from `FontFaceInfo`.
ickshonpe Dec 5, 2025
81a2456
Add debug + simpler example
ickshonpe Dec 5, 2025
265ba64
Clean up
ickshonpe Dec 5, 2025
50fea97
Added release note.
ickshonpe Dec 5, 2025
5c66154
clean up example
ickshonpe Dec 5, 2025
bd5b35b
Renamed font to pass CI
ickshonpe Dec 5, 2025
4b7a118
Merge branch 'main' into font-weight
ickshonpe Dec 5, 2025
35baf7d
added ; for formatting
ickshonpe Dec 5, 2025
beaa291
Merge branch 'font-weight' of https://github.com/ickshonpe/bevy into …
ickshonpe Dec 5, 2025
d16ddfe
Add PR number to release note
ickshonpe Dec 5, 2025
cb54d78
Merge branch 'main' into font-weight
ickshonpe Dec 6, 2025
7217021
Merge branch 'main' into font-weight
ickshonpe Dec 7, 2025
8e1cca5
Merge branch 'main' into font-weight
ickshonpe Dec 9, 2025
6218185
Merge branch 'main' into font-weight
ickshonpe Dec 9, 2025
c0ba51e
Merge branch 'main' into font-weight
ickshonpe Dec 9, 2025
3a44ae0
Fixed section info in `update_text_layout_info`.
ickshonpe Dec 10, 2025
a5ac340
Collapsed double if let statements
ickshonpe Dec 10, 2025
22b8d75
Removed trailing space from release note
ickshonpe Dec 10, 2025
cfa9a0f
Merge branch 'main' into font-weight
ickshonpe Dec 10, 2025
f467612
Added link to online css `font-weight` documentation.
ickshonpe Dec 10, 2025
03aba63
Merge branch 'font-weight' of https://github.com/ickshonpe/bevy into …
ickshonpe Dec 10, 2025
9c3378c
Update crates/bevy_text/src/text.rs
ickshonpe Dec 10, 2025
98e7db0
Use MonaSans variable font instead of NotoSans
ickshonpe Dec 10, 2025
cb8a25d
Merge branch 'font-weight' of https://github.com/ickshonpe/bevy into …
ickshonpe Dec 10, 2025
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
11 changes: 11 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3480,6 +3480,17 @@ description = "Demonstrates how Display and Visibility work in the UI."
category = "UI (User Interface)"
wasm = true

[[example]]
name = "font_weights"
path = "examples/ui/font_weights.rs"
doc-scrape-examples = true

[package.metadata.example.font_weights]
name = "Font Weights"
description = "Demonstrates how to use font weights."
category = "UI (User Interface)"
wasm = true

[[example]]
name = "window_fallthrough"
path = "examples/ui/window_fallthrough.rs"
Expand Down
Binary file added assets/fonts/MonaSans-VariableFont.ttf
Binary file not shown.
93 changes: 93 additions & 0 deletions assets/fonts/OFL.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
Copyright 2022 The Mona Sans Project Authors (https://github.com/github/mona-sans), with Reserved Font Name "Mona"

This 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:
https://openfontlicense.org


-----------------------------------------------------------
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.
4 changes: 2 additions & 2 deletions crates/bevy_text/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ pub use text_access::*;
pub mod prelude {
#[doc(hidden)]
pub use crate::{
Font, Justify, LineBreak, Strikethrough, StrikethroughColor, TextColor, TextError,
TextFont, TextLayout, TextSpan, Underline, UnderlineColor,
Font, FontWeight, Justify, LineBreak, Strikethrough, StrikethroughColor, TextColor,
TextError, TextFont, TextLayout, TextSpan, Underline, UnderlineColor,
};
}

Expand Down
45 changes: 17 additions & 28 deletions crates/bevy_text/src/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,6 @@ pub struct FontFaceInfo {
pub stretch: cosmic_text::fontdb::Stretch,
/// Allows italic or oblique faces to be selected
pub style: cosmic_text::fontdb::Style,
/// The degree of blackness or stroke thickness
pub weight: cosmic_text::fontdb::Weight,
/// Font family name
pub family_name: Arc<str>,
}
Expand All @@ -86,7 +84,7 @@ pub struct TextPipeline {
LineHeight,
)>,
/// Buffered vec for collecting info for glyph assembly.
glyph_info: Vec<(AssetId<Font>, FontSmoothing, f32, f32, f32, f32)>,
glyph_info: Vec<(AssetId<Font>, FontSmoothing, f32, f32, f32, f32, u16)>,
}

impl TextPipeline {
Expand Down Expand Up @@ -270,6 +268,7 @@ impl TextPipeline {
0.,
0.,
0.,
text_font.weight.clamp().0,
));
});

Expand All @@ -288,18 +287,13 @@ impl TextPipeline {

update_result?;

for (font, _, size, strikethrough_offset, stroke, underline_offset) in
for (font, _, size, strikethrough_offset, stroke, underline_offset, weight) in
self.glyph_info.iter_mut()
{
let Some((id, _)) = self.map_handle_to_font_id.get(font) else {
continue;
};
let weight = font_system
.db()
.face(*id)
.map(|f| f.weight)
.unwrap_or(cosmic_text::Weight::NORMAL);
if let Some(font) = font_system.get_font(*id, weight) {
if let Some(font) = font_system.get_font(*id, cosmic_text::Weight(*weight)) {
let swash = font.as_swash();
let metrics = swash.metrics(&[]);
let upem = metrics.units_per_em as f32;
Expand Down Expand Up @@ -528,23 +522,19 @@ impl TextPipeline {
0.0,
0.0,
0.0,
text_font.weight.clamp().0,
);

if let Some((id, _)) = self.map_handle_to_font_id.get(&section_info.0) {
let weight = font_system
.db()
.face(*id)
.map(|f| f.weight)
.unwrap_or(cosmic_text::Weight::NORMAL);
if let Some(font) = font_system.get_font(*id, weight) {
let swash = font.as_swash();
let metrics = swash.metrics(&[]);
let upem = metrics.units_per_em as f32;
let scalar = section_info.2 * scale_factor as f32 / upem;
section_info.3 = (metrics.strikeout_offset * scalar).round();
section_info.4 = (metrics.stroke_size * scalar).round().max(1.);
section_info.5 = (metrics.underline_offset * scalar).round();
}
if let Some((id, _)) = self.map_handle_to_font_id.get(&section_info.0)
&& let Some(font) = font_system.get_font(*id, cosmic_text::Weight(section_info.6))
Copy link
Member

Choose a reason for hiding this comment

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

let chain 🎉 👍

{
let swash = font.as_swash();
let metrics = swash.metrics(&[]);
let upem = metrics.units_per_em as f32;
let scalar = section_info.2 * scale_factor as f32 / upem;
section_info.3 = (metrics.strikeout_offset * scalar).round();
section_info.4 = (metrics.stroke_size * scalar).round().max(1.);
section_info.5 = (metrics.underline_offset * scalar).round();
}
self.glyph_info.push(section_info);
}
Expand Down Expand Up @@ -681,7 +671,7 @@ impl TextPipeline {
// Check result.
result?;

layout_info.size = box_size;
layout_info.size = box_size.ceil();
Ok(())
}
}
Expand Down Expand Up @@ -824,7 +814,6 @@ pub fn load_font_to_fontdb(
FontFaceInfo {
stretch: face.stretch,
style: face.style,
weight: face.weight,
family_name: family_name.clone(),
}
}
Expand All @@ -843,7 +832,7 @@ fn get_attrs<'a>(
.family(Family::Name(&face_info.family_name))
.stretch(face_info.stretch)
.style(face_info.style)
.weight(face_info.weight)
.weight(text_font.weight.into())
.metrics(
Metrics {
font_size: text_font.font_size,
Expand Down
73 changes: 73 additions & 0 deletions crates/bevy_text/src/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,10 @@ pub struct TextFont {
/// A new font atlas is generated for every combination of font handle and scaled font size
/// which can have a strong performance impact.
pub font_size: f32,
/// How thick or bold the strokes of a font appear.
///
/// Font weights can be any value between 1 and 1000, inclusive.
pub weight: FontWeight,
/// The antialiasing method to use when rendering text.
pub font_smoothing: FontSmoothing,
/// OpenType features for .otf fonts that support them.
Expand Down Expand Up @@ -308,12 +312,81 @@ impl Default for TextFont {
Self {
font: Default::default(),
font_size: 20.0,
weight: FontWeight::NORMAL,
font_features: FontFeatures::default(),
font_smoothing: Default::default(),
}
}
}

/// How thick or bold the strokes of a font appear.
///
/// Valid font weights range from 1 to 1000, inclusive.
/// Weights above 1000 are clamped to 1000.
/// A weight of 0 is treated as [`FontWeight::DEFAULT`].
///
/// `<https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/font-weight>`
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)]
pub struct FontWeight(pub u16);

impl FontWeight {
/// Weight 100.
pub const THIN: FontWeight = FontWeight(100);

/// Weight 200.
pub const EXTRA_LIGHT: FontWeight = FontWeight(200);

/// Weight 300.
pub const LIGHT: FontWeight = FontWeight(300);

/// Weight 400.
pub const NORMAL: FontWeight = FontWeight(400);

/// Weight 500.
pub const MEDIUM: FontWeight = FontWeight(500);

/// Weight 600.
pub const SEMIBOLD: FontWeight = FontWeight(600);

/// Weight 700.
pub const BOLD: FontWeight = FontWeight(700);

/// Weight 800
pub const EXTRA_BOLD: FontWeight = FontWeight(800);

/// Weight 900.
pub const BLACK: FontWeight = FontWeight(900);

/// Weight 950.
pub const EXTRA_BLACK: FontWeight = FontWeight(950);

/// The default font weight.
pub const DEFAULT: FontWeight = Self::NORMAL;

/// Clamp the weight value to between 1 and 1000.
/// Values of 0 are mapped to `Weight::DEFAULT`.
pub const fn clamp(mut self) -> Self {
if self.0 == 0 {
self = Self::DEFAULT;
} else if 1000 < self.0 {
self.0 = 1000;
}
Self(self.0)
}
}

impl Default for FontWeight {
fn default() -> Self {
Self::DEFAULT
}
}

impl From<FontWeight> for cosmic_text::Weight {
fn from(value: FontWeight) -> Self {
cosmic_text::Weight(value.clamp().0)
}
}

/// An OpenType font feature tag.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)]
pub struct FontFeatureTag([u8; 4]);
Expand Down
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,7 @@ Example | Description
[Feathers Widgets](../examples/ui/feathers.rs) | Gallery of Feathers Widgets
[Flex Layout](../examples/ui/flex_layout.rs) | Demonstrates how the AlignItems and JustifyContent properties can be composed to layout nodes and position text
[Font Atlas Debug](../examples/ui/font_atlas_debug.rs) | Illustrates how FontAtlases are populated (used to optimize text rendering internally)
[Font Weights](../examples/ui/font_weights.rs) | Demonstrates how to use font weights.
[Ghost Nodes](../examples/ui/ghost_nodes.rs) | Demonstrates the use of Ghost Nodes to skip entities in the UI layout hierarchy
[Gradients](../examples/ui/gradients.rs) | An example demonstrating gradients
[Overflow](../examples/ui/overflow.rs) | Simple example demonstrating overflow behavior
Expand Down
Loading