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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
use std::cmp;
use std::collections::BTreeMap;
use std::fmt;
use std::io::Read;
use std::path;
use gfx_glyph::FontId;
use image;
use image::RgbaImage;
use rusttype;
use super::*;
#[derive(Clone)]
pub enum Font {
TTFFont {
font: rusttype::Font<'static>,
points: u32,
scale: rusttype::Scale,
},
BitmapFontVariant(BitmapFont),
GlyphFont(FontId),
}
#[derive(Clone, Debug)]
pub struct BitmapFont {
bytes: Vec<u8>,
width: usize,
height: usize,
glyphs: BTreeMap<char, (usize, usize)>,
space_width: usize,
letter_separation: usize,
}
impl BitmapFont {
fn span_for(&self, c: char) -> usize {
match self.glyphs.get(&c) {
Some(&(_, span)) => span,
None => {
if c == ' ' {
self.space_width
} else {
0
}
}
}
}
}
impl Font {
pub fn new<P>(context: &mut Context, path: P, points: u32) -> GameResult<Font>
where
P: AsRef<path::Path> + fmt::Debug,
{
let mut stream = context.filesystem.open(path.as_ref())?;
let mut buf = Vec::new();
stream.read_to_end(&mut buf)?;
let name = format!("{:?}", path);
let (_diag_dpi, x_dpi, y_dpi) = context.gfx_context.dpi;
Font::from_bytes(&name, &buf, points, (x_dpi, y_dpi))
}
pub fn new_px<P>(context: &mut Context, path: P, pixels: u32) -> GameResult<Font>
where
P: AsRef<path::Path> + fmt::Debug,
{
let mut stream = context.filesystem.open(path.as_ref())?;
let mut buf = Vec::new();
stream.read_to_end(&mut buf)?;
let name = format!("{:?}", path);
Font::from_bytes_px(&name, &buf, pixels)
}
pub fn from_bytes(name: &str, bytes: &[u8], points: u32, dpi: (f32, f32)) -> GameResult<Font> {
let font_collection_err = &|_| {
GameError::ResourceLoadError(format!(
"Could not load font collection for \
font {:?}",
name
))
};
let collection =
rusttype::FontCollection::from_bytes(bytes.to_vec()).map_err(font_collection_err)?;
let font_err = &|_| {
GameError::ResourceLoadError(format!(
"Could not retrieve font from collection for \
font {:?}",
name
))
};
let font = collection.into_font().map_err(font_err)?;
let (x_dpi, y_dpi) = dpi;
let scale = display_independent_scale(points, x_dpi, y_dpi);
Ok(Font::TTFFont {
font,
points,
scale,
})
}
pub fn from_bytes_px(name: &str, bytes: &[u8], pixels: u32) -> GameResult<Font> {
let font_collection_err = &|_| {
GameError::ResourceLoadError(format!(
"Could not load font collection for \
font {:?}",
name
))
};
let collection =
rusttype::FontCollection::from_bytes(bytes.to_vec()).map_err(font_collection_err)?;
let font_err = &|_| {
GameError::ResourceLoadError(format!(
"Could not retrieve font from collection for \
font {:?}",
name
))
};
let font = collection.into_font().map_err(font_err)?;
let scale = rusttype::Scale {
x: pixels as f32,
y: pixels as f32,
};
Ok(Font::TTFFont {
points: 0,
font,
scale,
})
}
pub fn new_bitmap<P: AsRef<path::Path>>(
context: &mut Context,
path: P,
glyphs: &str,
) -> GameResult<Font> {
let img = {
let mut buf = Vec::new();
let mut reader = context.filesystem.open(path)?;
reader.read_to_end(&mut buf)?;
image::load_from_memory(&buf)?.to_rgba()
};
let (image_width, image_height) = img.dimensions();
let glyph_width = (image_width as usize) / glyphs.len();
let mut glyphs_map: BTreeMap<char, (usize, usize)> = BTreeMap::new();
for (i, c) in glyphs.chars().enumerate() {
glyphs_map.insert(c, (i * glyph_width, glyph_width));
}
Ok(Font::BitmapFontVariant(BitmapFont {
bytes: img.into_vec(),
width: image_width as usize,
height: image_height as usize,
glyphs: glyphs_map,
space_width: glyph_width,
letter_separation: 0,
}))
}
pub fn new_variable_width_bitmap_font<P: AsRef<path::Path>>(
context: &mut Context,
path: P,
glyphs: &str,
space_width: usize,
letter_separation: usize,
) -> GameResult<Font> {
let img = {
let mut buf = Vec::new();
let mut reader = context.filesystem.open(path)?;
reader.read_to_end(&mut buf)?;
image::load_from_memory(&buf)?.to_rgba()
};
let (image_width, image_height) = img.dimensions();
let mut glyphs_map: BTreeMap<char, (usize, usize)> = BTreeMap::new();
let mut start = 0usize;
let mut glyphos = glyphs.chars().enumerate();
let column_has_content = |offset: usize, image: &RgbaImage| {
(0..image_height).any(|ir| image.get_pixel(offset as u32, ir).data[3] > 0)
};
while start < image_width as usize {
if column_has_content(start, &img) {
let mut span = 1;
while start + span < image_width as usize && column_has_content(start + span, &img)
{
span += 1;
}
let next_char: char = glyphos
.next()
.ok_or_else(|| {
GameError::FontError("I counted more glyphs in the font bitmap than there were chars in the glyphs string. Note, glyphs must not have gaps. A glyph with a transparent column in the middle will read as two glyphs.".into())
})?
.1;
glyphs_map.insert(next_char, (start, span));
start += span;
}
start += 1;
}
let (lb, _) = glyphos.size_hint();
if lb > 0 {
return Err(GameError::FontError(
"There were more chars in glyphs than I counted in the bitmap!".into(),
));
}
Ok(Font::BitmapFontVariant(BitmapFont {
bytes: img.into_vec(),
width: image_width as usize,
height: image_height as usize,
glyphs: glyphs_map,
space_width,
letter_separation,
}))
}
pub fn new_glyph_font<P>(context: &mut Context, path: P) -> GameResult<Self>
where
P: AsRef<path::Path> + fmt::Debug,
{
let mut stream = context.filesystem.open(path.as_ref())?;
let mut buf = Vec::new();
stream.read_to_end(&mut buf)?;
let font_id = context.gfx_context.glyph_brush.add_font_bytes(buf);
Ok(Font::GlyphFont(font_id))
}
pub fn get_glyph_font_by_id(context: &mut Context, font_id: FontId) -> GameResult<Self> {
if context
.gfx_context
.glyph_brush
.fonts()
.contains_key(&font_id)
{
Ok(Font::GlyphFont(font_id))
} else {
Err(GameError::FontError(
format!("Font {:?} not found!", font_id).into(),
))
}
}
pub(crate) fn default_font_bytes() -> &'static [u8] {
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/resources/DejaVuSerif.ttf"
))
}
pub fn default_font() -> GameResult<Self> {
let size = 16;
Font::from_bytes("default", Font::default_font_bytes(), size, (75.0, 75.0))
}
pub fn get_height(&self) -> usize {
match *self {
Font::BitmapFontVariant(BitmapFont { height, .. }) => height,
Font::TTFFont { scale, .. } => scale.y.ceil() as usize,
Font::GlyphFont(_) => 0,
}
}
pub fn get_width(&self, text: &str) -> usize {
match *self {
Font::BitmapFontVariant(ref font) => {
compute_variable_bitmap_text_rendering_span(text, font)
}
Font::TTFFont {
ref font, scale, ..
} => {
let v_metrics = font.v_metrics(scale);
let offset = rusttype::point(0.0, v_metrics.ascent);
let glyphs: Vec<rusttype::PositionedGlyph> =
font.layout(text, scale, offset).collect();
text_width(&glyphs).ceil() as usize
}
Font::GlyphFont(_) => 0,
}
}
pub fn get_wrap(&self, text: &str, wrap_limit: usize) -> (usize, Vec<String>) {
let mut broken_lines = Vec::new();
for line in text.lines() {
let mut current_line = Vec::new();
for word in line.split_whitespace() {
let mut prospective_line = current_line.clone();
prospective_line.push(word);
let text = prospective_line.join(" ");
let prospective_line_width = self.get_width(&text);
if prospective_line_width > wrap_limit {
broken_lines.push(current_line.join(" "));
current_line.clear();
current_line.push(word);
} else {
current_line.push(word);
}
}
broken_lines.push(current_line.join(" "));
}
let max_line_length = broken_lines
.iter()
.map(|line| self.get_width(line))
.max()
.unwrap_or(1);
(max_line_length, broken_lines)
}
}
impl fmt::Debug for Font {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Font::TTFFont { .. } => write!(f, "<TTFFont: {:p}>", &self),
Font::BitmapFontVariant(BitmapFont { .. }) => write!(f, "<BitmapFont: {:p}>", &self),
Font::GlyphFont { .. } => write!(f, "<GlyphFont: {:p}>", &self),
}
}
}
#[derive(Clone)]
pub struct Text {
texture: Image,
contents: String,
blend_mode: Option<BlendMode>,
}
fn display_independent_scale(points: u32, dpi_w: f32, dpi_h: f32) -> rusttype::Scale {
let points = points as f32;
let points_per_inch = 72.0;
let pixels_per_point_w = dpi_w * (1.0 / points_per_inch);
let pixels_per_point_h = dpi_h * (1.0 / points_per_inch);
rusttype::Scale {
x: pixels_per_point_w * points,
y: pixels_per_point_h * points,
}
}
fn text_width(glyphs: &[rusttype::PositionedGlyph]) -> f32 {
glyphs
.iter()
.rev()
.filter_map(|g| {
g.pixel_bounding_box()
.map(|b| b.min.x as f32 + g.unpositioned().h_metrics().advance_width)
})
.next()
.unwrap_or(0.0)
}
fn render_ttf(
context: &mut Context,
text: &str,
font: &rusttype::Font<'static>,
scale: rusttype::Scale,
) -> GameResult<Text> {
let text_height_pixels = scale.y.ceil() as usize;
let v_metrics = font.v_metrics(scale);
let offset = rusttype::point(0.0, v_metrics.ascent);
let glyphs: Vec<rusttype::PositionedGlyph> = font.layout(text, scale, offset).collect();
let text_width_pixels = cmp::max(text_width(&glyphs).ceil() as usize, 1);
let bytes_per_pixel = 4;
let mut pixel_data = vec![0; text_width_pixels * text_height_pixels * bytes_per_pixel];
let pitch = text_width_pixels * bytes_per_pixel;
for g in glyphs {
if let Some(bb) = g.pixel_bounding_box() {
g.draw(|x, y, v| {
let c = (v * 255.0) as u8;
let x = x as i32 + bb.min.x;
let y = y as i32 + bb.min.y;
if x >= 0 && x < text_width_pixels as i32 && y >= 0 && y < text_height_pixels as i32
{
let x = x as usize * bytes_per_pixel;
let y = y as usize;
pixel_data[(x + y * pitch)] = 255;
pixel_data[(x + y * pitch + 1)] = 255;
pixel_data[(x + y * pitch + 2)] = 255;
pixel_data[(x + y * pitch + 3)] = c;
}
})
}
}
assert!(text_width_pixels < u16::MAX as usize);
assert!(text_height_pixels < u16::MAX as usize);
let image = Image::from_rgba8(
context,
text_width_pixels as u16,
text_height_pixels as u16,
&pixel_data,
)?;
let text_string = text.to_string();
Ok(Text {
texture: image,
contents: text_string,
blend_mode: None,
})
}
#[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
fn blit(
dst: &mut [u8],
dst_dims: (usize, usize),
dst_point: (usize, usize),
src: &[u8],
src_dims: (usize, usize),
src_point: (usize, usize),
rect_size: (usize, usize),
pitch: usize,
) {
let area_row_width = rect_size.0 * pitch;
let src_row_width = src_dims.0 * pitch;
let dst_row_width = dst_dims.0 * pitch;
for row_idx in 0..rect_size.1 {
let src_row = row_idx + src_point.1;
let dst_row = row_idx + dst_point.1;
let src_offset = src_row * src_row_width + (src_point.0 * pitch);
let dst_offset = dst_row * dst_row_width + (dst_point.0 * pitch);
let dst_slice = &mut dst[dst_offset..(dst_offset + area_row_width)];
let src_slice = &src[src_offset..(src_offset + area_row_width)];
dst_slice.copy_from_slice(src_slice);
}
}
struct VariableFontCharIter<'a> {
font: &'a BitmapFont,
iter: ::std::str::Chars<'a>,
offset: usize,
}
impl<'a> Iterator for VariableFontCharIter<'a> {
type Item = (char, usize, usize);
fn next(&mut self) -> Option<Self::Item> {
if let Some(c) = self.iter.next() {
let char_span = self.font.span_for(c);
let this_offset = self.offset;
self.offset += char_span + self.font.letter_separation;
Some((c, this_offset, char_span))
} else {
None
}
}
}
impl<'a> VariableFontCharIter<'a> {
fn new(text: &'a str, font: &'a BitmapFont) -> VariableFontCharIter<'a> {
VariableFontCharIter {
font,
iter: text.chars(),
offset: 0,
}
}
}
fn compute_variable_bitmap_text_rendering_span(text: &str, font: &BitmapFont) -> usize {
VariableFontCharIter::new(text, font)
.last()
.map(|(_, offset, span)| offset + span)
.unwrap_or(0)
}
fn render_dynamic_bitmap(context: &mut Context, text: &str, font: &BitmapFont) -> GameResult<Text> {
let image_span = compute_variable_bitmap_text_rendering_span(text, font);
let buf_len = cmp::max(image_span * font.height * 4, 1);
let mut dest_buf = Vec::with_capacity(buf_len);
dest_buf.resize(buf_len, 0u8);
for (c, offset, _) in VariableFontCharIter::new(text, font) {
let (coffset, cspan) = *font.glyphs.get(&c).unwrap_or(&(0, 0));
blit(
&mut dest_buf,
(image_span, font.height),
(offset, 0),
&font.bytes,
(font.width, font.height),
(coffset, 0),
(cspan, font.height),
4,
);
}
let image = Image::from_rgba8(context, image_span as u16, font.height as u16, &dest_buf)?;
let text_string = text.to_string();
Ok(Text {
texture: image,
contents: text_string,
blend_mode: None,
})
}
impl Text {
pub fn new(context: &mut Context, text: &str, font: &Font) -> GameResult<Text> {
match *font {
Font::TTFFont {
font: ref f, scale, ..
} => render_ttf(context, text, f, scale),
Font::BitmapFontVariant(ref font) => render_dynamic_bitmap(context, text, font),
Font::GlyphFont(_) => Err(GameError::FontError(
"`Text` can't be created with a `Font::GlyphFont` (yet)!".into(),
)),
}
}
pub fn width(&self) -> u32 {
self.texture.width()
}
pub fn height(&self) -> u32 {
self.texture.height()
}
pub fn contents(&self) -> &str {
&self.contents
}
pub fn get_dimensions(&self) -> Rect {
self.texture.get_dimensions()
}
pub fn get_filter(&self) -> FilterMode {
self.texture.get_filter()
}
pub fn set_filter(&mut self, mode: FilterMode) {
self.texture.set_filter(mode);
}
pub fn get_image(&self) -> &Image {
&self.texture
}
pub fn get_image_mut(&mut self) -> &mut Image {
&mut self.texture
}
pub fn into_inner(self) -> Image {
self.texture
}
}
impl Drawable for Text {
fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()> {
draw_ex(ctx, &self.texture, param)
}
fn set_blend_mode(&mut self, mode: Option<BlendMode>) {
self.blend_mode = mode;
}
fn get_blend_mode(&self) -> Option<BlendMode> {
self.blend_mode
}
}
impl fmt::Debug for Text {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"<Text: {}x{}, {:p}>",
self.texture.width, self.texture.height, &self
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_blit() {
let dst = &mut [0; 125][..];
let src = &[
1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 1, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
][..];
assert_eq!(src.len(), 25 * 5);
let rect_dims = (25, 5);
blit(dst, rect_dims, (0, 0), src, rect_dims, (0, 0), (25, 5), 1);
assert_eq!(dst, src);
for i in 0..dst.len() {
dst[i] = 0;
}
let rect_dims = (5, 5);
blit(dst, rect_dims, (0, 0), src, rect_dims, (0, 0), (5, 5), 5);
assert_eq!(dst, src);
}
#[test]
fn test_metrics() {
let f = Font::default_font().expect("Could not get default font");
assert_eq!(f.get_height(), 17);
assert_eq!(f.get_width("Foo!"), 34);
let text_to_wrap = "Walk on car leaving trail of paw prints on hood and windshield sniff \
other cat's butt and hang jaw half open thereafter for give attitude. \
Annoy kitten\nbrother with poking. Mrow toy mouse squeak roll over. \
Human give me attention meow.";
let (len, v) = f.get_wrap(text_to_wrap, 250);
println!("{} {:?}", len, v);
assert_eq!(len, 250);
let wrapped_text = vec![
"Walk on car leaving trail of paw",
"prints on hood and windshield",
"sniff other cat\'s butt and hang jaw",
"half open thereafter for give",
"attitude. Annoy kitten",
"brother with poking. Mrow toy",
"mouse squeak roll over. Human",
"give me attention meow.",
];
assert_eq!(&v, &wrapped_text);
}
#[allow(dead_code)]
fn test_wrapping() {
use conf;
let c = conf::Conf::new();
let ctx = &mut Context::load_from_conf("test_wrapping", "ggez", c)
.expect("Could not create context?");
let font = Font::default_font().expect("Could not get default font");
let text_to_wrap = "Walk on car leaving trail of paw prints on hood and windshield sniff \
other cat's butt and hang jaw half open thereafter for give attitude. \
Annoy kitten\nbrother with poking. Mrow toy mouse squeak roll over. \
Human give me attention meow.";
let wrap_length = 250;
let (len, v) = font.get_wrap(text_to_wrap, wrap_length);
assert!(len < wrap_length);
for line in &v {
let t = Text::new(ctx, line, &font).unwrap();
println!(
"Width is claimed to be <= {}, should be <= {}, is {}",
len,
wrap_length,
t.width()
);
assert!(t.width() as usize <= wrap_length);
}
}
}