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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
//! This module draws text gizmos using a stroke font.
use crate::simplex_stroke_font::*;
use crate::{gizmos::GizmoBuffer, prelude::GizmoConfigGroup};
use bevy_color::Color;
use bevy_math::{vec2, Isometry2d, Isometry3d, Vec2};
use core::ops::Range;
/// A stroke font containing glyphs for the 95 printable ASCII codes.
pub struct StrokeFont<'a> {
/// Baseline-to-baseline line height ratio.
pub line_height: f32,
/// Full glyph height (cap + descender) in font units.
pub height: f32,
/// Cap height in font units.
pub cap_height: f32,
/// Advance used for unsupported glyphs.
pub advance: i8,
/// Raw glyph point positions.
pub positions: &'a [[i8; 2]],
/// Stroke ranges into `positions`.
pub strokes: &'a [Range<usize>],
/// Glyph advances and stroke ranges.
pub glyphs: &'a [(i8, Range<usize>); 95],
}
impl<'a> StrokeFont<'a> {
/// Builds a `StrokeTextLayout` for `sections` at the requested `font_size`.
pub fn layout(
&'a self,
sections: &'a [(&'a str, Color)],
font_size: f32,
) -> StrokeTextLayout<'a> {
let scale = font_size / SIMPLEX_CAP_HEIGHT;
let glyph_height = SIMPLEX_HEIGHT * scale;
let line_height = LINE_HEIGHT * glyph_height;
let margin_top = line_height - glyph_height;
let space_advance = SIMPLEX_GLYPHS[0].0 as f32 * scale;
let tab_advance = space_advance * TAB_WIDTH_IN_SPACES as f32;
StrokeTextLayout {
font: self,
sections,
scale,
line_height,
margin_top,
space_advance,
tab_advance,
}
}
fn get_glyph_index(&self, c: char) -> Option<usize> {
let code = c as u32;
if (0x20..=0x7E).contains(&code) {
Some(code as usize - 0x20)
} else {
None
}
}
/// Get the advance and stroke point ranges for a glyph.
pub fn get_glyph(&self, c: char) -> Option<(i8, Range<usize>)> {
Some(self.glyphs[self.get_glyph_index(c)?].clone())
}
/// Get the advance for a glyph.
pub fn get_glyph_advance(&self, c: char) -> Option<i8> {
Some(self.glyphs[self.get_glyph_index(c)?].0)
}
}
/// Stroke text layout
pub struct StrokeTextLayout<'a> {
/// The unscaled font
font: &'a StrokeFont<'a>,
/// The text sections with per-section colors.
sections: &'a [(&'a str, Color)],
/// Scale applied to the raw glyph positions.
scale: f32,
/// Height of each line of text.
line_height: f32,
/// Space between top of line and cap height.
margin_top: f32,
/// Width of a space.
space_advance: f32,
/// Width of a tab stop.
tab_advance: f32,
}
impl<'a> StrokeTextLayout<'a> {
/// Computes the width and height of the text layout.
///
/// Returns the layout size in pixels.
pub fn measure(&self) -> Vec2 {
let mut layout_size = vec2(0., self.line_height);
let mut line_width = 0.;
for (c, _) in colored_chars(self.sections) {
if c == '\n' {
layout_size.x = layout_size.x.max(line_width);
line_width = 0.;
layout_size.y += self.line_height;
continue;
}
if c == '\t' {
line_width = next_tab_stop(line_width, self.tab_advance);
continue;
}
line_width += self
.font
.get_glyph_advance(c)
.map(|advance| advance as f32 * self.scale)
.unwrap_or(self.space_advance);
}
layout_size.x = layout_size.x.max(line_width);
layout_size
}
/// Returns an iterator over the font strokes for this text layout, grouped into polylines
/// of `Vec2` points, each paired with its color from the text sections.
pub fn render(&'a self) -> impl Iterator<Item = (Color, impl Iterator<Item = Vec2> + 'a)> + 'a {
let mut chars = colored_chars(self.sections);
let mut x = 0.0_f32;
let mut y = -self.margin_top;
let mut current_strokes: Range<usize> = 0..0;
let mut current_x = 0.0_f32;
let mut current_color = Color::WHITE;
core::iter::from_fn(move || loop {
for stroke_index in current_strokes.by_ref() {
let stroke = self.font.strokes[stroke_index].clone();
if stroke.len() < 2 {
continue;
}
// If this stroke is a closed loop, append one extra point to add a join at the seam.
let join = (self.font.positions[stroke.start]
== self.font.positions[stroke.end - 1])
.then_some(stroke.start + 1);
let color = current_color;
return Some((
color,
stroke.chain(join).map(move |index| {
let [p, q] = self.font.positions[index];
Vec2::new(
current_x + self.scale * p as f32,
y - self.scale * (self.font.cap_height - q as f32),
)
}),
));
}
let (c, char_color) = chars.next()?;
if c == '\n' {
x = 0.0;
y -= self.line_height;
continue;
}
if c == '\t' {
x = next_tab_stop(x, self.tab_advance);
continue;
}
let Some((advance, strokes)) = self.font.get_glyph(c) else {
x += self.space_advance;
continue;
};
current_color = char_color;
current_strokes = strokes;
current_x = x;
x += advance as f32 * self.scale;
})
}
}
impl<Config, Clear> GizmoBuffer<Config, Clear>
where
Config: GizmoConfigGroup,
Clear: 'static + Send + Sync,
{
/// Draw text using a stroke font with the given isometry applied.
///
/// Only ASCII characters in the range 32–126 are supported.
///
/// # Arguments
///
/// - `isometry`: defines the translation and rotation of the text.
/// - `text`: the text to be drawn.
/// - `size`: the size of the text in pixels.
/// - `anchor`: normalized anchor point relative to the text bounds,
/// where `(0, 0)` is centered, `(-0.5, 0.5)` is top-left,
/// and `(0.5, -0.5)` is bottom-right.
/// - `color`: the color of the text.
///
/// # Example
/// ```
/// # use bevy_gizmos::prelude::*;
/// # use bevy_math::prelude::*;
/// # use bevy_color::Color;
/// fn system(mut gizmos: Gizmos) {
/// gizmos.text(Isometry3d::IDENTITY, "text gizmo", 25., Vec2::ZERO, Color::WHITE);
/// }
/// # bevy_ecs::system::assert_is_system(system);
/// ```
pub fn text(
&mut self,
isometry: impl Into<Isometry3d>,
text: &str,
font_size: f32,
anchor: Vec2,
color: impl Into<Color>,
) {
let color: Color = color.into();
self.text_sections(isometry, &[(text, color)], font_size, anchor);
}
/// Draw text using a stroke font with the given isometry applied, coloring each section
/// independently.
///
/// Only ASCII characters in the range 32–126 are supported.
///
/// # Arguments
///
/// - `isometry`: defines the translation and rotation of the text.
/// - `sections`: a slice of `(text, color)` pairs. Each section's characters are drawn
/// in its color. Sections are concatenated left-to-right on the same baseline.
/// - `font_size`: the size of the text in pixels.
/// - `anchor`: normalized anchor point relative to the combined text bounds,
/// where `(0, 0)` is centered, `(-0.5, 0.5)` is top-left,
/// and `(0.5, -0.5)` is bottom-right.
///
/// # Example
/// ```
/// # use bevy_gizmos::prelude::*;
/// # use bevy_math::prelude::*;
/// # use bevy_color::Color;
/// fn system(mut gizmos: Gizmos) {
/// gizmos.text_sections(
/// Isometry3d::IDENTITY,
/// &[("Hello ", Color::WHITE), ("World!", Color::srgb(1., 0.3, 0.))],
/// 25.,
/// Vec2::ZERO,
/// );
/// }
/// # bevy_ecs::system::assert_is_system(system);
/// ```
pub fn text_sections(
&mut self,
isometry: impl Into<Isometry3d>,
sections: &[(&str, Color)],
font_size: f32,
anchor: Vec2,
) {
let isometry: Isometry3d = isometry.into();
let layout = SIMPLEX_STROKE_FONT.layout(sections, font_size);
let layout_anchor = layout.measure() * (vec2(-0.5, 0.5) - anchor);
for (color, points) in layout.render() {
self.linestrip(
points.map(|point| isometry * (layout_anchor + point).extend(0.)),
color,
);
}
}
/// Draw text using a stroke font in 2d with the given isometry applied.
///
/// Only ASCII characters in the range 32–126 are supported.
///
/// # Arguments
///
/// - `isometry`: defines the translation and rotation of the text.
/// - `text`: the text to be drawn.
/// - `size`: the size of the text.
/// - `anchor`: normalized anchor point relative to the text bounds,
/// where `(0., 0.)` is centered, `(-0.5, 0.5)` is top-left,
/// and `(0.5, -0.5)` is bottom-right.
/// - `color`: the color of the text.
///
/// # Example
/// ```
/// # use bevy_gizmos::prelude::*;
/// # use bevy_math::prelude::*;
/// # use bevy_color::Color;
/// fn system(mut gizmos: Gizmos) {
/// gizmos.text_2d(Isometry2d::IDENTITY, "2D text gizmo", 25., Vec2::ZERO, Color::WHITE);
/// }
/// # bevy_ecs::system::assert_is_system(system);
/// ```
pub fn text_2d(
&mut self,
isometry: impl Into<Isometry2d>,
text: &str,
font_size: f32,
anchor: Vec2,
color: impl Into<Color>,
) {
let color: Color = color.into();
self.text_sections_2d(isometry, &[(text, color)], font_size, anchor);
}
/// Draw text using a stroke font in 2d with the given isometry applied, coloring each section
/// independently.
///
/// Only ASCII characters in the range 32–126 are supported.
///
/// # Arguments
///
/// - `isometry`: defines the translation and rotation of the text.
/// - `sections`: a slice of `(text, color)` pairs. Each section's characters are drawn
/// in its color. Sections are concatenated left-to-right on the same baseline.
/// - `font_size`: the size of the text.
/// - `anchor`: normalized anchor point relative to the combined text bounds,
/// where `(0., 0.)` is centered, `(-0.5, 0.5)` is top-left,
/// and `(0.5, -0.5)` is bottom-right.
///
/// # Example
/// ```
/// # use bevy_gizmos::prelude::*;
/// # use bevy_math::prelude::*;
/// # use bevy_color::Color;
/// fn system(mut gizmos: Gizmos) {
/// gizmos.text_sections_2d(
/// Isometry2d::IDENTITY,
/// &[("Hello ", Color::WHITE), ("World!", Color::srgb(1., 0.3, 0.))],
/// 25.,
/// Vec2::ZERO,
/// );
/// }
/// # bevy_ecs::system::assert_is_system(system);
/// ```
pub fn text_sections_2d(
&mut self,
isometry: impl Into<Isometry2d>,
sections: &[(&str, Color)],
font_size: f32,
anchor: Vec2,
) {
let isometry: Isometry2d = isometry.into();
let layout = SIMPLEX_STROKE_FONT.layout(sections, font_size);
let layout_anchor = layout.measure() * (vec2(-0.5, 0.5) - anchor);
for (color, points) in layout.render() {
self.linestrip_2d(
points.map(|point| isometry * (layout_anchor + point)),
color,
);
}
}
}
/// Iterates the characters across all sections, each paired with its section color.
fn colored_chars<'a>(sections: &'a [(&'a str, Color)]) -> impl Iterator<Item = (char, Color)> + 'a {
sections
.iter()
.flat_map(|&(text, color)| text.chars().map(move |c| (c, color)))
}
fn next_tab_stop(x: f32, tab_advance: f32) -> f32 {
let tab_index = (x / tab_advance).floor() as i64 + 1;
tab_index as f32 * tab_advance
}